Last modified: Mar 30, 2026 By Alexander Williams

Fix Python IndexError List Index Out of Range

You are writing Python code. Your program suddenly crashes. It prints a confusing error: IndexError: list index out of range. This is a very common error for beginners. It can be frustrating. But do not worry. This guide will explain it clearly.

We will break down what this error means. You will see common causes. We will provide simple solutions. By the end, you will know how to fix and prevent this error.

What Does "List Index Out of Range" Mean?

In Python, a list is an ordered collection of items. Each item has a position, called an index. Indexing starts at 0. The first item is at index 0. The second is at index 1, and so on.

An IndexError happens when you try to access an index that does not exist. The list is "out of range" of its valid indices. Think of it like trying to read page 10 in a 5-page book. The page does not exist.

Here is a simple example that causes the error.


# Example 1: Basic IndexError
my_list = ['apple', 'banana', 'cherry']
print(my_list[3])  # Trying to access the fourth element (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 is out of range. Python cannot find it, so it raises an error.

Common Causes of the IndexError

Understanding why the error occurs is the first step to fixing it. Here are the most frequent causes.

1. Off-by-One Errors with Loops

This is the most common cause. You use a loop to go through a list. But your loop counter goes one step too far. It tries to access an index equal to the list's length.

Remember: The last valid index is len(list) - 1.


# Example 2: Off-by-one in a for loop
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits) + 1):  # range goes 0, 1, 2, 3
    print(fruits[i])               # Error on i=3!

The range() function is often involved here. If you need a refresher on how it works, check our Python Range Function Guide.

2. Assuming a List is Not Empty

You try to access the first item with my_list[0]. But what if the list is empty? An empty list has no indices at all. Accessing index 0 will cause an IndexError.


# Example 3: Accessing an empty list
empty_list = []
first_item = empty_list[0]  # IndexError!

3. Incorrect List Manipulation

You might remove items from a list while looping over it. This changes the list's length. Your loop counter may then point to an invalid index.


# Example 4: Modifying list during iteration
numbers = [10, 20, 30, 40, 50]
for i in range(len(numbers)):
    if numbers[i] > 25:
        del numbers[i]  # Deleting changes list size!
    print(numbers[i])

How to Debug and Fix the IndexError

Now you know the causes. Let's find solutions. Follow these steps to debug your code.

Step 1: Check the List Length

Use the len() function. Print the length of your list before the error line. This tells you the maximum valid index.


my_list = ['a', 'b', 'c']
print(f"List length: {len(my_list)}")  # Output: 3
print(f"Last valid index: {len(my_list) - 1}")  # Output: 2

Step 2: Review Your Loop Conditions

If using a for loop with range(), ensure the stop value is correct. It should typically be len(list). The range() function generates numbers up to, but not including, the stop value. For clarity on this behavior, see our article Is Python Range Inclusive?.


# Correct way to loop by index
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):  # i will be 0, 1, 2
    print(fruits[i])

Step 3: Use Direct Iteration (Pythonic Way)

Often, you don't need the index at all. You can loop directly over the list items. This avoids index errors completely.


# Better: Loop directly over items
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)  # No index used!

If you need the index and the item, use enumerate().


# Using enumerate for index and value
for index, fruit in enumerate(fruits):
    print(f"Index {index} has {fruit}")

Step 4: Check for Empty Lists

Before accessing an index, verify the list is not empty. Use an if statement.


safe_list = []
if safe_list:  # Checks if list has items
    first_item = safe_list[0]
else:
    print("The list is empty.")

Advanced Example: A Common Pitfall

Let's look at a more complex example. It involves user input and list processing. This shows how errors can sneak in.


# Example: Processing user input with potential error
user_input = input("Enter numbers separated by spaces: ")
# user_input could be "10 20 30" or it could be ""
number_strings = user_input.split()  # Creates a list of strings
numbers = []

for i in range(len(number_strings)):
    # What if number_strings is empty? len() is 0, range(0) is empty.
    # The loop won't run, so no error here.
    numbers.append(float(number_strings[i]))

# Now let's try to access the 'middle' element.
mid_index = len(numbers) // 2  # Integer division
print(f"The middle number is {numbers[mid_index]}")  # Potential IndexError if numbers is empty!

If the user enters nothing, numbers remains an empty list. The line numbers[mid_index] will fail because mid_index is 0. The fix is to check if the list has elements first.

Best Practices to Prevent IndexError

Prevention is better than cure. Follow these tips to write robust code.

1. Prefer Iteration Over Indexing: Use for item in my_list or enumerate() whenever possible.

2. Use Exception Handling (try-except): Catch the error if you are unsure about the list state. This makes your program more stable.


try:
    value = my_list[5]
except IndexError:
    print("That index doesn't exist. Using a default value.")
    value = None

3. Validate List Size Before Access: Always check len(my_list) before using a calculated index.

4. Be Careful with List Modifications: Avoid changing a list's length while iterating over it by index. If you must, consider iterating over a copy of the list or using a while loop.

Understanding sequences is key. If you're working with non-integer steps, you might explore concepts like the Python Range Float for specialized cases, though it's not directly related to list indexing.

Conclusion

The IndexError: list index out of range is a fundamental Python error. It teaches you about list boundaries and careful programming. Remember, list indices start at 0 and end at len(list)-1.

To fix it, check your list length. Review your loop conditions. Use Pythonic iteration with for loops and enumerate(). Always guard against empty lists.

Do not fear this error. See it as a helpful message. It points you directly to a line where your assumption about the list's content was wrong. With the techniques from this guide, you can debug it quickly and write stronger, error-resistant code.