Module 3 · Operations on lists · Lesson 3 of 5
Slices with negative indices
Remember that a single negative index counts from the end: nums[-1] is the last item. The lovely part is that this works inside a slice too, so you can describe a stretch relative to the end without ever knowing the list's length.
nums[-3:-1]The blue numbers below are the negative indices. -3 up to (not including) -1 gives you 30 and 40.
Each box has two indices: the usual one counting up from 0 on top, and the negative one counting back from -1 underneath. A slice can use either — or mix them. The stop is still excluded, so nums[-3:-1] stops just before the last element.
Two patterns worth keeping in your pocket: nums[-2:] for “the last couple,” and the famous nums[::-1] — a step of -1 that walks the list backwards and hands you a reversed copy.