Home >Backend Development >Python Tutorial >Python's detailed introduction to list slicing
This article mainly introduces the usage of Python list slicing, and analyzes the common operation methods and related precautions of Python list slicing in the form of examples. Friends in need can refer to it
The examples in this article describe Python list slicing usage. Share it with everyone for your reference, the details are as follows:
All ordered sequences that conform to the sequence in Python support slices, such as lists, strings, and tuples.
Format: [start:end:step]
start: starting index, starting from 0, -1 means the end
end: end index
step: step, end-start, when the step is positive, the value is taken from left to right. When the step size is negative, the reverse value is taken
Note that the result of slicing does not include the end index, that is, it does not include the last bit. -1 represents the last position index of the list
a=[1,2,3,4,5,6] b1=a[:] #省略全部,代表截取全部内容,可以用来将一个列表拷给另一个列表 print(b1)
Result: [1, 2, 3, 4, 5, 6]
b=a[0:-1:1] #从位置0开始到结束,每次增加1,截取。不包含结束索引位置 print(b)
Result: [1, 2, 3, 4, 5]
c1=a[:3] #省略起始位置的索引,以及步长。默认起始位置从头开始,默认步长为1,结束位置索引为3 print(c1)
Result: [1, 2, 3]
c=a[0:5:3] #从第一个位置到第留给位置,每3个取一个值 print(c)
Result: [1, 4]
d=a[5:0:-1] #反向取值 print(d)
Result: [6, 5, 4, 3, 2]
d1=a[::-1] print(d1)
Result: [6, 5, 4, 3, 2, 1]
The above is the detailed content of Python's detailed introduction to list slicing. For more information, please follow other related articles on the PHP Chinese website!