Gangmax Blog

Python slice to reverse

I read some Python code lines from here like below:

1
2
# reverse the order of path, such that it starts with [0, 0]
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
2
3
>>> path = [(0, 0), (0, 1), (0, 2), (0, 3)]
>>> path[::-1]
[(0, 3), (0, 2), (0, 1), (0, 0)]

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

1
2
class slice(stop)
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