0

I have a list like this:

list = ['a', 'b', 'c']

I want the first element only, by using a list slicer that counts down. That is:

list[start:stop:-1]

What do I set as start and stop to return exactly ['a']?

My first intuition would be list[0:-1:-1], but this returns an empty list.

Anna Madsen
  • 384
  • 3
  • 15
  • (Don't shadow `list`, but...) `list[:1]`? – jonrsharpe Dec 09 '22 at 13:13
  • Why do you want to do this? You could do `my_list[-3::-1]` but that is very ugly. – John Coleman Dec 09 '22 at 13:17
  • *What do I set as start and stop to return exactly `['a']`?* - you probably know that `list[0]` returns `'a'`, and `list[0:1]` returns `['a']`. Then with negative indices: `list[-3]` returns`'a'`, and `list[-3:-2]` returns `['a']`. Where `-3` is actually `-len(list)+0`, and `-2` is `-len(list)+1`, from the original `[0:1]`. If you want it to count downwards, it can be `list[-3:-4:-1]`. – tevemadar Dec 09 '22 at 13:58
  • I found the correct notation: `list[0::-1]` – Anna Madsen Dec 09 '22 at 14:15

0 Answers0