The method you used is called Slicing
in Python.
Slicing syntax in python is as follows,
[ <first element to include> : <first element to exclude> : <step> ]
where adding the step
part is optional.
Here is a representation of how python list considers positive and negative index.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
When using,
a = range(10)
# a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a[10:0:-1] #or
a[-1:-10:-1]
# Output = [9, 8, 7, 6, 5, 4, 3, 2, 1]
Why because, when we give 0
/-10
as the second parameter, it excludes the element in the 0
/-10
th position.
So easy way is to omit the second parameter in slicing. That is,
a[10::-1] #or
a[-1::-1]
# Output = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Which is what we want.
In order to further simplify, if you omit both start and end value and just give step as -1, it again yields the same result.
a[::-1]
# Output = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# The -1 at step position traverse the element from the last to the beginning
Here is a simple cheat sheet for understanding Slicing,
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
a[start:end:step] # start through not past end, by step
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
To understand more about slicing, see this
Hope this helps! :)