0

Suppose a=[1,2,3,4,5]. If we write a[len(a):-1:-1], following the slicing rule [start:end:step size], why do we get an empty list? However, a[len(a)::-1] returns an reversed list [5,4,3,2,1].

Please give me an explanation.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Because if you start at `len(a)` (beyond the end of the list) and end at `-1` (the last item in the list) going `-1` (backwards), there are no elements to include in the result. – jonrsharpe Aug 16 '23 at 20:02
  • 1
    So, your stop could be `0`, the beginning of the list, but since the stop is non-inclusive, it would omit the first element `1`! you tried to use `-1`. But that is actually the last element of the list! So you have to actually use `None`, e.g. `[len(a):None:-1]` . But the idiomatic way is just `[::-1]` which is equivalent to `[None:None: -1]` – juanpa.arrivillaga Aug 16 '23 at 20:09

0 Answers0