Editor

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

Broken
colors = ['red', 'green', 'blue']
print(colors[3])
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
IndexError: list index out of range

The fix

Fixed
colors = ['red', 'green', 'blue']
print(colors[2]) # the third item is at position 2
print(colors[-1]) # -1 is always the last item
Output
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.

Try fixing it yourself in the editor

2. Reading from an empty list

This raises the error

Broken
scores = []
best = scores[0]
print(best)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
IndexError: list index out of range

The fix

Fixed
scores = []
if scores:
print('Best:', scores[0])
else:
print('No scores yet')
Output
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.

Try fixing it yourself in the editor

3. A loop that goes one step too far

This raises the error

Broken
nums = [10, 20, 30]
for i in range(len(nums) + 1):
print(nums[i])
Output
10
20
30
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
IndexError: list index out of range

The fix

Fixed
nums = [10, 20, 30]
for i in range(len(nums)): # 0, 1, 2
print(nums[i])
for n in nums: # simpler: loop over the items
print(n)
Output
10
20
30
10
20
30

range(len(nums)) already stops at the last position. Looping over the list itself avoids positions altogether.

Try fixing it yourself in the editor

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 items or enumerate() instead of range(len()).

All Python errors · How to read a traceback · Step through your code