Reputation: 297
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
Upvotes: 3
Views: 29814
Reputation: 45
A -ve value in any python sequences means :
Val = len(sequence)+(-ve value)
Either start/stop from/to len(sequence)+(-ve value)
, depending on what we specify.
Upvotes: 0
Reputation: 304137
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
Upvotes: 10
Reputation: 767
-1 does not go back to the first term in a tuple
x=(1,2,3,4,5)
x[-1]
yields
5
Upvotes: 14
Reputation: 34146
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.
Upvotes: 5