Given that -1 goes back to the first term in a tuple, and the end index of a slice stops before that index, why does
x=(1,2,3,4,5)
x[0:-1]
yield
(1, 2, 3, 4)
instead of stopping at the index before the first which is 5?
Thanks
Given that -1 goes back to the first term in a tuple, and the end index of a slice stops before that index, why does
x=(1,2,3,4,5)
x[0:-1]
yield
(1, 2, 3, 4)
instead of stopping at the index before the first which is 5?
Thanks
It helps to think of the slicing points as between the elements
x = ( 1, 2, 3, 4, 5 )
| | | | | |
0 1 2 3 4 5
-5 -4 -3 -2 -1
Slicing works like this:
x[start : end : step]
In your example, start = 0
, so it will start from the beginning, end = -1
it means that the end will be the last element of the tuple (not the first). You are not specifying step
so it will its default value 1
.
This link from Python docs may be helpful, there are some examples of slicing.