Python error explained
IndexError: what it means and how to fix it
You asked for a position that does not exist in the list.
The message
IndexError: list index out of range
What it means
Lists count from 0, so a list of 3 items has positions 0, 1 and 2. Asking for position 3 or more, or for anything in an empty list, raises an IndexError.
Common causes
- Forgetting that the first item is at 0
- Using len(items) as an index (the last one is len(items) - 1)
- A loop that goes one step too far
- Reading from a list that turned out to be empty
Example that raises it
podium = ["Ada", "Grace", "Linus"]
print("Gold:", podium[1])
print("Silver:", podium[2])
print("Bronze:", podium[3])
The fix
podium = ["Ada", "Grace", "Linus"]
print("Gold:", podium[0])
print("Silver:", podium[1])
print("Bronze:", podium[2])
Tip: Use podium[-1] for the last item, and loop with for item in podium so you never need the positions at all.
Fix the broken version yourself in the editor on this page. It runs real Python in your browser.