3
>> 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?

Oleg Razgulyaev
  • 5,757
  • 4
  • 28
  • 28
  • 2
    I'd argue it's more "pythonic" to use [9, 8, 7, 6, 5, 4, 3, 2, 1, 0].reverse() . In Python the focus should usually be on readability. – SpliFF May 01 '12 at 04:31
  • 3
    Or even `reversed(aSeq)` if you want the efficiency of an iterator – jdi May 01 '12 at 04:32
  • @SpliFF - they do slightly different things though. – detly May 01 '12 at 04:48
  • @SpliFF, `[::-1]` works for strings too though. I think it's a good idiom to know because `''.join(reversed(mystr))` isn't exactly readable either – John La Rooy May 01 '12 at 06:08

3 Answers3

11

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]
GWW
  • 43,129
  • 11
  • 115
  • 108
4

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.

Community
  • 1
  • 1
2

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.

Community
  • 1
  • 1
the wolf
  • 34,510
  • 13
  • 53
  • 71