4

I can't find any information on [::-1]. In the wikibooks python tutorial, there is a section about non-continous lists, but there's no information on parameters < 0. Effects are clear, but how do you explain it?

Example Usage:

>>> foo = [1, 2, 3]
>>> foo[::-1]
[3, 2, 1]
f4lco
  • 3,728
  • 5
  • 28
  • 53

3 Answers3

8

The syntax is as follows:

foo[start:end:step] # begin with 'start' and proceed by step until you reach 'end'.

So foo[::-1] means entire list with step=-1, so actually reversing the list.

See this answer for detailed explanation.

Community
  • 1
  • 1
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
2

Just one thing to add is that:

foo[::-1]

creates a copy of given array without affecting foo itself One may assign it as follows:

foo = [1,2,3]
bar = foo[::-1]
# print foo --> [1,2,3]
# print bar --> [3,2,1]

But to update foo, using:

foo.reverse()

is preferred

yan
  • 196
  • 1
  • 9
2

Negative step behaves the same as in range(start, stop, step). The thing to remember about negative step is that stop is always the excluded end, whether it's higher or lower.

It frequently surprises people that '0123456789'[5:0:-1] == '54321', not '43210'. If you want some sub-sequence, just in opposite order, it's much cleaner to do the reversal separately. E.g. slices off one char from left, two from right, then reverse: '0123456789'[1:-2][::-1] == '7654321' s. If you don't need a copy, just want to loop, it even more readable with reversed():

for char in reversed('0123456789'[1:-2]):
    ...
Beni Cherniavsky-Paskin
  • 9,483
  • 2
  • 50
  • 58