-1

I looked for answers but couldn't find anything.

>my_list = [7,8,9]
>my_list[2:1:-1]
[9]
>my_list[2:0:-1]
[9, 8]
>my_list[2:-1:-1]
[] # I would expect [9, 8, 7]

I am aware there are other ways to reverse a list, but I'm curious why the above doesn't work? my_list[2,None,-1] does work.

  • I don't think `my_list[2,1,-1]` is a valid syntax for indexing, did you mean `my_list[2:1:-1]` ? – David Yappeter Mar 09 '22 at 01:24
  • Does this answer your question? [Reversing a list using slice notation](https://stackoverflow.com/questions/5876998/reversing-a-list-using-slice-notation) – David Yappeter Mar 09 '22 at 01:27
  • @DavidYappeter thanks fixed the notation. Unfortunately not, I am specifically wondering why the `-1` exclusive boundary doesn't work – Josh Hinkle Mar 09 '22 at 01:30
  • according to the question above second element mean `first element to exclude`, which mean you if you place it with `0`, it will ignore first element, and if you place `-1` which mean the 'last element' and that is index `2`(your start of iteration) in your case, it will be an empty array, `None` will works – David Yappeter Mar 09 '22 at 01:33
  • @DavidYappeter Yeah kind of confusing. I would think "first element to exclude" being the last element would mean include the first element. I would read it as include elements `2, 1, 0` and do not include -1 – Josh Hinkle Mar 09 '22 at 01:36

1 Answers1

0

If you want to iterate from the back until the first element, leave the second element empty: my_list[2::-1] well or write it sorter my_list[::-1]

David Yappeter
  • 1,434
  • 3
  • 15