IndexError: list index out of range
You asked for an index the list does not have. Almost always a loop bound that is one too far, or an empty list you assumed had items.
What it means
Python lists are indexed from 0, so a list of 5 items has valid indices 0 to 4. Asking for index 5 — or any index at or beyond the length — raises IndexError immediately. Unlike JavaScript, which quietly returns undefined, Python fails loudly at the exact line, which is genuinely helpful once you know what it means.
Common causes
1. A loop that runs one time too many
range(len(items) + 1) or a while loop testing <= length both step one past the end.
Breaks
for i in range(len(items) + 1):
print(items[i])Works
for i in range(len(items)):
print(items[i])2. Using the length as an index
The last valid index is len - 1. len itself is always one past the end.
Breaks
last = items[len(items)]Works
last = items[len(items) - 1] # or items[-1]3. The list is empty
items[0] fails on an empty list. This is common when a filter or an API call returned nothing.
Breaks
first = results[0]Works
first = results[0] if results else None4. Removing items while looping over them
The list shrinks as you iterate, so the index eventually points past the new end.
Breaks
for i in range(len(items)):
if items[i] < 0:
items.pop(i)Works
items = [x for x in items if x >= 0]How to find it in your own code
Print len(items) and the index right before the failing line. If the index equals the length, your bound is one too far. If the length is 0, the real bug is upstream — something returned nothing and you did not check.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.