IndexError: list index out of range
What it means
You asked for a position the list does not have. Positions start at 0, so a list of 3 items has positions 0, 1 and 2, and items[3] is past the end; an empty list has no positions at all. If the message says list assignment index, you tried to store a value at a missing position, and append() is the way to add items.
1. Counting from 1 instead of 0
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> IndexError: list index out of range
The fix
blue blue
The last position is len(colors) - 1, here 2. Negative positions count from the end, so colors[-1] is the last item whatever the length.
2. Reading from an empty list
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> IndexError: list index out of range
The fix
No scores yet
An empty list counts as false in an if, so the check reads scores[0] only when there is something to read.
3. A loop that goes one step too far
This raises the error
10 20 30 Traceback (most recent call last): File "<exec>", line 3, in <module> IndexError: list index out of range
The fix
10 20 30 10 20 30
range(len(nums)) already stops at the last position. Looping over the list itself avoids positions altogether.
When you see this error, check
- Print
len(your_list)and the index just before the failing line. - Remember the last position is
len(list) - 1, or simply-1. - Check that the list is not empty before reading
[0]. - Use
append()to add new items: assigning to a position that does not exist fails. - Loop with
for item in itemsorenumerate()instead ofrange(len()).
Related errors
All Python errors · How to read a traceback · Step through your code