The full notation of slice in Python is the following:
s[start:end:step]
That being said it provides useful defaults for the values, as per the documentation:
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
So when you do something like:
s[1:]
under the hood this is done:
s[1:len(s)]
Note that in both cases step defaults to 1
. In most languages when you want to access the last element of a list for example you do something like:
s[len(s) - 1]
Python negative indexing is a sort of syntactic sugar on that notation so :
l[-1] = l[len(l) - 1]
l[-2] = l[len(l) - 2]
...
Then when you do:
l[-3:]
this is done:
l[len(l)-3:len(l)]
So, instead of 0
you should use len(l)
as the last index:
l = [1, 2, 3, 4, 5]
print(l[-3:len(l)])
Output
[3, 4, 5]
Note that l[-3:0]
returns the empty list because len(l) - 3 > 0
, i.e. the first index is greater than the second and step is 1
.
Further
- Understanding Python's slice notation