How to Fix IndexError: list index out of range in Python
In this tutorial, you'll learn about How to Fix IndexError: list index out of range in Python. We cover key concepts, practical examples, and best practices.
Python raises IndexError: list index out of range when you try to access an element at an index that exceeds the length of the sequence.
The Wrong Way
items = [10, 20, 30]
print(items[5])
This produces:
Traceback (most recent call last):
File "script.py", line 2, in <module>
print(items[5])
IndexError: list index out of range
The Right Way
Check the list length before accessing an index:
items = [10, 20, 30]
index = 5
if index < len(items):
print(items[index])
else:
print(f"Index {index} out of range")
Output:
Index 5 out of range
Step-by-Step Fix
1. Verify the sequence length
items = [10, 20, 30]
print(len(items)) # 3
Valid indices are 0 through len(items) - 1. Index 3 is out of range for a 3-element list.
2. Check loop boundaries
# Wrong
items = [10, 20, 30]
for i in range(len(items) + 1): # goes up to index 3
print(items[i])
# Right
for i in range(len(items)):
print(items[i])
3. Use negative indexing safely
Negative indices wrap around but still have bounds:
items = [10, 20, 30]
print(items[-1]) # 30 -- last element
print(items[-4]) # IndexError -- only 3 elements
4. Use try-except for dynamic access
items = [10, 20, 30]
index = 10
try:
print(items[index])
except IndexError:
print(f"Index {index} is out of range for list of length {len(items)}")
Prevention Tips
- Always check
index < len(sequence)before direct access. - Use
enumerate()when iterating with indices. - Use negative indices (
-1,-2) to access from the end safely. - For pop operations, check
if list:before calling.pop(). - Use
sequence[-1]to access the last element instead ofsequence[len(sequence)-1].
Common Mistakes with indexerror
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro