How to Fix IndexError - List Index Out of Range in Python
Last Updated :
23 Jul, 2025
IndexError: list index out of range is a common error in Python when working with lists. This error happens when we try to access an index that does not exist in the list. This article will explore the causes of this error, how to fix it and best practices for avoiding it.
Example:
Python
a = [1, 2, 3]
print(a[3]) # IndexError
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
IndexError: list index out of range
Causes of IndexError: List Index Out of Range
This error usually occurs under the following conditions:
1. Accessing an index that exceeds the length of the list
Python
a = [1, 2, 3]
print(a[5]) # IndexError
2. Accessing a negative index that doesn’t exist
Python
a = [1, 2, 3]
print(a[-4]) # IndexError
3. Iterating over a list incorrectly using loops
Python
a = [1, 2, 3]
for i in range(len(a) + 1): # Incorrect range
# IndexError when i = 3
print(a[i])
How to Fix IndexError
Here’s how we can resolve and avoid this error with examples:
1. Check the List Length Before Accessing
Always verify the length of the list before accessing an index.
Python
a = [10, 20, 30]
# Let suppose we want to access 'idx' index
idx = 2
if len(a) > idx:
print(a[idx]) # Safe access
else:
print("Index out of range")
2. Use Negative Indexes Correctly
Negative indexes start from the end of the list. So, make sure that index don’t exceed the list boundaries.
Python
a = [10, 20, 30]
try:
# Valid negative index
print(a[-1])
# Invalid negative index
print(a[-4])
except IndexError:
print("Negative index is out of range.")
Output30
Negative index is out of range.
3. Iterate Safely in Loops
When iterating over a list make sure that index don’t exceed the list boundaries.
Python
a = [10, 20, 30]
for i in range(len(a)):
print(a[i])
4. Use Enumerate for Safe Iteration
Enumerate provides the index and value of a list and this index will never go out of bounds.
Python
a = [10, 20, 30]
for idx, val in enumerate(a):
print(f"Index: {idx}, Value: {val}")
OutputIndex: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
5. Use Try-Except to Handle Errors
Using a try-except block we can prevent our program to crash and allows us to handle errors easily.
Python
a = [10, 20, 30]
# Let suppose we want to access 'idx' index
idx = 3
try:
print(a[idx])
except IndexError:
print("Index is out of range. Please check your list.")
OutputIndex is out of range. Please check your list.
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS