All Python errors
IndexError in Python: list index out of range
IndexError means you asked for a position that does not exist in a list or a string. To fix it, remember that counting starts at 0: a list of 3 items has indexes 0, 1 and 2, and the last one is also available as -1.
Code with the error
days = ["Mon", "Tue", "Wed"]
print(days[3])
Error message (Python 3.12, last line)
Corrected code
days = ["Mon", "Tue", "Wed"]
print(days[len(days) - 1])
Output
Wed
Common causes
- Counting from 1 instead of 0.
- Using len(items) as an index.
- Taking an item from an empty list.
- A loop goes one step too far, for example with items[i + 1].
Practise in the course
Lesson: ListsFrequently asked questions
How do I get the last item safely?
Use items[-1]. It works for any list that is not empty.
Does slicing raise IndexError?
No. A slice such as items[0:10] simply returns the items that exist.