Negative indexes (x[-1])
A negative index counts from the end: x[-1] is the last item, x[-2] the second to last.
Used in 73 lessons of the course, from 00.06.
In a sequence (list, string, tuple) each item has two positions: one counted from the start (0, 1, 2…) and one counted from the end (-1, -2, -3…).
x[-1] is the last item. x[-2] is the one before it. It helps because you don't need to know how many items there are: you don't have to write x[len(x) - 1].
The negative index -n is the same as len(x) - n. That's why the valid range is -len(x) to len(x) - 1. Outside it, Python raises IndexError.
In the course you see it in lines like text.split("## [Production Models]")[-1]. split returns a list of pieces, and [-1] takes the last one: what comes after the last separator, however many pieces there are.
names = ["a", "b", "c"]
print(names[-1]) # c
Reach for it when: you want the last item (or one near the end) and you don't care how many items there are.
Examples
Common mistake
items = [] print(items[-1])
Why: An empty list has no last item, so not even -1 exists.
How to write it: Check first with if items: and then use items[-1].
