>> a = range(10)
>> print a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This slice gives reversed list. How does it work?
>> a = range(10)
>> print a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This slice gives reversed list. How does it work?
The third argument is a step modifier. In this case you are using a step of -1
.
You could also use a step of 2
to print every even index.
>>> a = range(10)
>>> a[::2]
[0, 2, 4, 6, 8]
>>> a[::-2]
[9, 7, 5, 3, 1]
Once you grok extended slices, be sure to appreciate the under appreciated slice() function:
>>> for sl in [(1,-1),(0,20,3),(10,),(None,None,-3),(None,None,4)]:
... print range(20)[slice(*sl)]
...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[0, 3, 6, 9, 12, 15, 18]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[19, 16, 13, 10, 7, 4, 1]
[0, 4, 8, 12, 16]
It is especially useful for fixed length data formats.
This is the extended slice syntax. See the docs.
For range(x,y,z)
x is the start, y is the stop, z is the stride.
This has been covered well in this SO post.