What does extended slice syntax actually do for negative steps? [duplicate] What does extended slice syntax actually do for negative steps? [duplicate] python python

What does extended slice syntax actually do for negative steps? [duplicate]


[-1:0:-1] means: start from the index len(string)-1 and move up to 0(not included) and take a step of -1(reverse).

So, the following indexes are fetched:

le-1, le-1-1, le-1-1-1  .... 1  # le is len(string)

example:

In [24]: strs = 'foobar'In [25]: le = len(strs)In [26]: strs[-1:0:-1]  # the first -1 is equivalent to len(strs)-1Out[26]: 'raboo'In [27]: strs[le-1:0:-1]   Out[27]: 'raboo'


The Python documentation (here's the technical one; the explanation for range() is a bit easier to understand) is more correct than the simplified "every kth element" explanation. The slicing parameters are aptly named

slice[start:stop:step]

so the slice starts at the location defined by start, stops before the location stop is reached, and moves from one position to the next by step items.