Gangmax Blog

自由之思想,独立之精神

Python slice to reverse

I read some Python code lines from here like below:

1
# reverse the order of path, such that it starts with [0, 0]
2
return path[::-1]

I was not quite sure about the meaning of the “[::-1] part, so I did some test and figured it out:

1
>>> path = [(0, 0), (0, 1), (0, 2), (0, 3)]
2
>>> path[::-1]
3
[(0, 3), (0, 2), (0, 1), (0, 0)]

Actually that is the built-in “slice()“ function of Python:

1
class slice(stop)
2
class slice(start, stop[, step])

So:

  1. One argument, it’s “stop”.

  2. Two arguments, they’re “start” and “stop”.

  3. Three arguments, they’re “start”, “stop” and “step”.

Comments