I am new to Python and have read several tutorials on slicing however the examples I run in idle don't seem to return what I expect it to. For example I have assigned the follow list to the variable a
a=[0,1,2,3,4,5,6,7,8,9]
Now I understand slicing to be as [number I want to include:number up to and don't want to include:step]
Hence if I do a[1], I would expect 1. If I do a[1:3], it would be 1,2
Now if I do a[-1], I get 9 BUT if I do a[-1:-5], I get nothing. All I see is []. why is that? I would expect to see 9,8,7,6
I am running Python 2.7 on Windows 7 Professional
In this case, you would need to add in the step argument in order to get what you want:
In [1]: a=[0,1,2,3,4,5,6,7,8,9]
In [2]: a[-1:-5:-1]
Out[2]: [9, 8, 7, 6]
And if you want to save a bit more space, you can omit the first argument:
In [3]: a[:-5:-1]
Out[3]: [9, 8, 7, 6]
The way that Python handles the 'negative' slices is that it adds then len of the object to the negative number. So when you say In a[-1:-5], it is basically saying a[(-1+10):(-5+10)], which equals a[9:5], and since start/end refers to all characters between the two (moving 'forward' through the list), it doesn't return anything (hence your blank list). You can see this by doing something like:
In [5]: a[-5:9]
Out[5]: [5, 6, 7, 8]
In [6]: a[5:9]
Out[6]: [5, 6, 7, 8]
You get the same result with the negative and positive indices, since -5 + 10 = 5.
Providing the -1 step argument tells it to start at the first element but move backwards from the start position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With