: Application in python native list
Usually a slice operation needs to provide three parameters [start:stop:step]
start is the starting position of the slice
stop is the end position of the slice (not included)
The step can be omitted, the default value is 1, and the step value cannot be 0, otherwise an error will be reported.
ValueError: slice step cannot be zero
list=[1,2,3,4,5,6,7,8,9]
When step is a positive number, start from the element position of list[start], and use step as the step length to the element position (not included) of list[stop_], intercepting from left to right. Both start and stop are positive or negative indexes or mixed, but to ensure that the [logical] position of the list[stop] element must be to the right of the [logical] position of the list[start] element, otherwise the element cannot be retrieved.
print(list[0:4])
[0, 1, 2, 3]
print(list[1:-1])
[1, 2, 3, 4, 5, 6, 7, 8]
print(list[-8:8])
[2, 3, 4, 5, 6, 7]
When step is a negative number, start from the position of the list[start] element, and use step as the step length to the position of the list[stop] element (not included), intercepting from right to left, to ensure the [logic] of the list[stop] element position
It must be on the left of the [logical] position of the list[start] element, otherwise the element cannot be retrieved.
print(list[5:2:-1])
[5, 4, 3]
print(list[7:-7:-1])
[7, 6, 5, 4]
When start and stop conform to the virtual logical position relationship, the absolute value of start and stop can be greater than length.
print(list[-12:5:2])
[0, 2, 4]
Both start and stop can be omitted. For example, list[:], the omitted ones will be intercepted by the starting elements of the corresponding left and right boundaries by default.
print(list[:])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Insert an element at a certain position
list[3:3]="a"print(list)
[0, 1, 2, ' a', 3, 4, 5, 6, 7, 8, 9]
list[5:5]=["a","b"]print(list)
[0, 1, 2, 3, 4, ' a', 'b', 5, 6, 7, 8, 9]
Recommended Posts