on slices, negative indices, which are the equivalent procedures?
Jach Feng
jfong at ms4.hinet.net
Thu Aug 5 23:05:29 EDT 2021
> >>>>> s = "Jack Brandom"
> >>>>> s[3 : -13 : -1]
> >> 'kcaJ'
> >> I have no idea how to replace that -13 with a positive index. Is it
> >> possible at all?
That's not possible because a positive index is relative to the leftmost item 0
Below is some rules of slice usage which I collected sometimes ago.
-----
slice s[i:j:k]
The result is from start index i to stop index j (excluded) in step k (default is 1). i, j, k can be positive or negative. For example: s = [1, 2, 3, 4, 5]
1. Positive index is relative to the leftmost item (0), negative index is relative to the rightmost item (-1). Note: out-of-range index is valid.
s[-4:5] == s[1:5] == [2,3,4,5] # index 5 is out-of-range
s[4:-6:-1] == [5,4,3,2,1] # index -6 is out-of-range
2. The default index of i and j (When index is omitted) was decided by the sign of k.
For positive k, the start index is 0 (the leftmost item) and the stop index is the one after the rightmost item.
s[:3] == s[0:3] == [1,2,3]
s[1:] == s[1:5] == [2,3,4,5]
For negative k, the start index is -1 (the rightmost item) and the stop index is one ahead of the leftmost item
s[:2:-1] == s[-1:2:-1] == [5,4]
s[3::-1] == s[3:-6:-1] == [4,3,2,1]
3. The items pick-up order was decided by the sign of k. For positive k, the direction is toward the right. For negative k, it is toward the left.
s[1:4] == [2,3,4]
s[3:0:-1] == [4,3,2]
4. Invalid slice will return an empty []
s[2:0] == []
-----
--Jach
More information about the Python-list
mailing list