An IndexError is raised in Python when you try to access a list (or other sequence) using an index that is out of bounds. The index you used is either too large or too small for the length of the sequence.
Why it happens
- •Accessing an index greater than or equal to the length of the list.
- •Using a negative index that goes further back than the start of the list.
- •Iterating off-by-one errors when building indices manually.
- •Assuming a list has elements when it might be empty.
Examples
Code that triggers the error
items = ["apple", "banana", "cherry"]
print(items[5])Error output
Traceback (most recent call last):
File "app.py", line 2, in <module>
print(items[5])
IndexError: list index out of rangeHow to fix it
Check the length of the list before accessing an index with len(). Use negative indexing (-1 for last element) only when the list is guaranteed to be non-empty. When iterating, prefer for item in list over manual index arithmetic.
Fixed code
items = ["apple", "banana", "cherry"]
# Check length before accessing
if len(items) > 5:
print(items[5])
else:
print("Index out of range")
# Or use a safe helper
last = items[-1] # last element is always safe if list is non-emptyRelated errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free