This article mainly introduces the usage of Python list slicing and analyzes the common operations and precautions of Python list slicing in the form of examples, for more information about how to use Python list slicing, see the next article. The following describes how to use Python list slicing in combination with examples.
This example describes how to use Python list slicing. We will share this with you for your reference. The details are as follows:
Slice is supported for ordered sequences in Python, such as lists, strings, and tuples.
Format: [start: end: step]
Start: start Index, starting from 0.-1 indicates the end.
End: end index
Step: step size, end-start, and the step size is positive. The value ranges from left to right. If the step size is negative, the reverse value is used.
Note that the slice result does not contain the ending index, that is, it does not contain the last digit.-1 indicates the index of the last position in the list.
A = [1, 2, 3, 4, 5, 6] b1 = a [:] # omitting all indicates intercepting all the content. you can copy one list to another and print (b1) it)
Result: [1, 2, 3, 4, 5, 6]
B = a [0:-] # from the position 0 to the end, increase by 1 each time and intercept. Excluding the ending index position print (B)
Result: [1, 2, 3, 4, 5]
C1 = a [: 3] # omit the index at the starting position and step size. The default start position starts from the beginning, the default step is 1, and the end position Index is 3 print (c1)
Result: [1, 2, 3]
C = a [] # from the first position to the left position, take a print (c) value for each three)
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 a detailed description of the list slice in Python. For more information, see other related articles in the first PHP community!