How this pythonic trick works: [:: - 1]

>> a = range(10)
>> print a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This snippet displays a reverse list. How it works?

+3
source share
3 answers

The third argument is the step modifier. In this case, you use the step -1.

You can also use the step 2to print each even index.

>>> a = range(10)
>>> a[::2]
[0, 2, 4, 6, 8]
>>> a[::-2]
[9, 7, 5, 3, 1]
+11
source

After you type the extended snippets, be sure to evaluate the underrated slice () :

>>> 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]

This is especially useful for fixed-length formats .

+4
source

. . .

range(x,y,z) x - , y - , z - .

SO.

+2

All Articles