I thought I understood the basics of list slicing in python, but have been receiving an unexpected error while using a negative step on a slice, as follows:
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[:-1:-1]
[]
(Note that this is being run in Python 3.5)
Why doesn't a[:-1:-1] reverse step through the a[:-1] slice in the same manner as it does through the whole list with a[::-1]?
I realize that you can use list.reverse() as well, but trying to understand the underlying python slice functionality better.
a[-1::-1]
. The first index gives the start, the second index gives the end, and you want to start at index -1. – jakevdp Jan 2 '17 at 17:17[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
– Ash Jan 2 '17 at 17:26a[::-1]
? – ekhumoro Jan 2 '17 at 17:28a[-2::-1]
(produces[8, 7, 6, 5, 4, 3, 2, 1, 0]
) is probably actually the answer, since the starting index is included. – Ash Jan 2 '17 at 17:30a[-2::-1]
is the solution I was looking for, but I didn't understand it fully until the discussion below about how the +/- sign of the step impacted the behavior of the ends. – Matt Kelty Jan 2 '17 at 18:10