IndexError in Python — What It Means and How to Fix It
What Python's IndexError exception means and how to resolve it.
Published October 27, 2026
IndexError is raised when you access a list or tuple index that does not exist.
What it means and why it happens
Typical causes: off-by-one errors, empty lists or assuming a minimum length.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
IndexError: list index out of range
Practical examples
Code that triggers it
items = [1, 2, 3]
print(items[3])The fix
items = [1, 2, 3]
print(items[-1])
if len(items) > 3: print(items[3])Safe first element
first = items[0] if items else None
first = next(iter(items), None)Common mistakes
- Off-by-one: last index is len-1.
- Indexing an empty list.
- Modifying a list while looping.
Key takeaways
- IndexError: IndexError is raised when you access a list or tuple index that does not exist.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
Last element?
items[-1] if the list is not empty.
How do I find which line caused IndexError?
The error message and stack trace show the file and line; start there and work backwards.