Question

Why an sliced list of negative step (or stride) can't get the whole list?

>>> my_list = range(1,11)
>>> reverse_list = my_list[10:0:-1]
>>> reverse_list
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>> reverse_list = my_list[11:0:-1]
>>> reverse_list
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>> reverse_list = my_list[11:-1:-1]
>>> reverse_list
[]
>>> 

But, if omitted start and end it works!

>>> reverse_list = my_list[::-1]
>>> reverse_list
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Was it helpful?

Solution

Because the end index 0 is not included.

The better way, as you stated, is:

>>> my_list[10::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Or you can use None (as @MartijnPieters suggested):

>>> my_list[10:None:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top