Last modified: Mar 28, 2026 By Alexander Williams
Fix Python List Index Out of Range Error
You are writing Python code. Suddenly, your program crashes. It shows an error: IndexError: list index out of range. This is a very common error for beginners. It can be frustrating. But it is easy to understand and fix.
This article will explain this error. You will learn what causes it. You will see examples. You will also learn how to prevent it in your code.
What Does "List Index Out of Range" Mean?
In Python, a list is an ordered collection of items. Each item has a position. This position is called an index. Python list indices start at 0. The first item is at index 0. The second is at index 1, and so on.
The error happens when you try to access an index that does not exist. You ask for the fifth item in a list of three. Python cannot find it. It raises an IndexError.
Think of a bookshelf with three books. You try to grab the fifth book. Your hand will grab nothing. The "list index out of range" error is Python's way of saying your hand grabbed air.
Common Causes of the IndexError
Let's look at the main reasons this error occurs.
1. Using an Index Number That is Too High
This is the most direct cause. You use an index number larger than the last valid index.
# Example 1: Index too high
my_list = [10, 20, 30]
print(my_list[3]) # Trying to access index 3
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
The list has three items: indices 0, 1, and 2. Index 3 does not exist. The error tells us this.
2. Off-by-One Errors in Loops
This is a classic mistake. You use a loop like a for loop with range(). You get the length of the list. But you use it incorrectly. For more on loops, see our Python Range Function Guide: Syntax & Examples.
# Example 2: Off-by-one in a for loop
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits) + 1): # +1 causes the error
print(fruits[i])
apple
banana
cherry
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
The loop runs for i = 0, 1, 2, 3. When i is 3, fruits[3] fails. The last valid index is 2.
3. Lists That Are Empty
An empty list has no items. Its length is 0. Trying to access any index, even index 0, will cause this error.
# Example 3: Accessing an empty list
empty_list = []
print(empty_list[0]) # There is no first item!
IndexError: list index out of range
4. Mistakes with List Methods
Methods like pop() can cause this error if used carelessly. The pop() method removes and returns an item at a given index. If the index is invalid, it raises the error.
# Example 4: Using pop() with a bad index
numbers = [5, 10]
removed_item = numbers.pop(2) # Tries to pop index 2
print(removed_item)
IndexError: pop index out of range
How to Fix and Prevent the Error
Now you know the causes. Let's find solutions. These techniques will help you write safer code.
1. Check the List Length Before Accessing
Always know how many items are in your list. Use the len() function. Make sure your index is less than the length.
# Fix: Check length first
my_list = [10, 20, 30]
index_to_access = 3
if index_to_access < len(my_list):
print(my_list[index_to_access])
else:
print(f"Index {index_to_access} is out of range. List length is {len(my_list)}.")
Index 3 is out of range. List length is 3.
2. Use a For-Each Loop When Possible
If you just need the items, not the index, use a direct loop. This prevents off-by-one errors.
# Fix: Loop directly over list items
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # No index to worry about
print(fruit)
apple
banana
cherry
3. Use Try-Except to Handle Errors Gracefully
Sometimes you can't avoid a potential error. Use a try-except block. This catches the IndexError and lets your program continue.
# Fix: Use try-except
data = [100, 200]
try:
value = data[5]
print(value)
except IndexError:
print("Could not retrieve the item. The index was invalid.")
Could not retrieve the item. The index was invalid.
4. Be Careful with List Modifications in Loops
Changing a list while looping over it is risky. If you remove items, the list gets shorter. Your loop index might become out of range. One solution is to loop over a copy of the list.
# Safe way to modify a list in a loop
numbers = [1, 2, 3, 4, 5]
numbers_to_remove = [2, 4]
for num in numbers[:]: # Loop over a slice copy
if num in numbers_to_remove:
numbers.remove(num) # Modify the original list
print(numbers) # Original list is modified safely
[1, 3, 5]
Debugging Tips for IndexError
When you get the error, don't panic. Follow these steps to find the bug.
Step 1: Read the Traceback. The error message shows the line number. Go to that line in your code.
Step 2: Print the List and Index. Just before the error line, add print statements. Print the list. Print its length. Print the index you are trying to use.
# Debugging example
my_list = get_data_from_somewhere() # A function that returns a list
idx = calculate_index() # A function that returns an index
print(f"List: {my_list}") # Check the list contents
print(f"List length: {len(my_list)}") # Check the length
print(f"Trying index: {idx}") # Check the index
# The problematic line
item = my_list[idx]
Step 3: Check Loop Conditions. If the error is in a loop, check your range() or while condition. Remember, range(len(list)) goes from 0 to len(list)-1.
Step 4: Verify List Contents. Make sure your list is not empty when you think it has data. A function might return an empty list under certain conditions.
Conclusion
The "list index out of range" error is a fundamental Python lesson. It teaches you about list boundaries and careful programming. The key is to remember that list indices start at 0 and end at length-1.
To avoid it, check lengths, use direct loops, and handle potential errors. Use debugging prints to see what your code is doing. With practice, you will make this error less often.
Understanding this error makes you a better programmer. It helps you write more robust and reliable Python code. Keep these solutions in mind. Your future self will thank you when your programs run smoothly.