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
stepargument in order to get what you want:And if you want to save a bit more space, you can omit the first argument:
The way that Python handles the ‘negative’ slices is that it adds then
lenof the object to the negative number. So when you say Ina[-1:-5], it is basically sayinga[(-1+10):(-5+10)], which equalsa[9:5], and sincestart/endrefers 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:You get the same result with the negative and positive indices, since
-5 + 10 = 5.Providing the -1
stepargument tells it to start at the first element but move backwards from the start position.