0

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]
Cœur
  • 37,241
  • 25
  • 195
  • 267
Trimax
  • 2,413
  • 7
  • 35
  • 59

1 Answers1

3

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]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • Or you can use `None`. – Martijn Pieters May 03 '14 at 15:21
  • `>>> my_list = range(1,11) >>> reverse_list = my_list[10:-1:-1] >>> reverse_list []` Don't works – Trimax May 03 '14 at 15:22
  • 1
    Note that `-1` as an endpoint translates to `len(my_list) - 1`, **not** a literal `-1`! Slicing from `[10:-1:-1]` then is the same as `[10:9:-1]` which is an *empty slice*. – Martijn Pieters May 03 '14 at 15:24
  • @MartijnPieters, Yes I was trying it out and just realized. I have updated my answer. – sshashank124 May 03 '14 at 15:25
  • @Trimax, I have removed that suggestion. Please see my updated answer. – sshashank124 May 03 '14 at 15:25
  • @MartijnPieters Yes, with None at end point it works fine. But, why not with 0 or -1? – Trimax May 03 '14 at 15:26
  • @Trimax, With `0`, it does not include it. Just like range(1,11) gets from 1 to 10 and not from 1 to 11. For -1, it takes it as the syntax `[-1]` which gets the last element of the list. Best way would be to do `[::-1]` – sshashank124 May 03 '14 at 15:27
  • 1
    @Trimax: The end index is not included, so you'd step from 10, to 9, to 8, etc. to 1. Then stop, because 0 as endpoint is excluded. `None` or leaving it empty means the default, which is 'until exhausted'. – Martijn Pieters May 03 '14 at 15:28
  • Thanks to both @MartijnPieters and sshashank124 ! – Trimax May 03 '14 at 15:31
  • @Trimax, No problem. Glad to have helped. – sshashank124 May 03 '14 at 15:32
  • 1
    @Trimax: negative indices are always translated to be relative to the length. So -1 really means length_of_the_list minus 1, in this case 9. Stepping down from 10, 9 is not included in the list. Remember that 9 is the highest index in a 0-based indexing system, not 10! – Martijn Pieters May 03 '14 at 15:32
  • @Trimax: but `[9:-11:-1]` works again to produce the whole list in reverse.. – Martijn Pieters May 03 '14 at 15:34