Home Tips How to Fix IndexError: list index out of range in Python (Beginner Guide)

How to Fix IndexError: list index out of range in Python (Beginner Guide)

The IndexError: list index out of range is one of the most common Python errors beginners encounter. It happens when your code tries to access an index in a list (or other sequence types like tuples) that doesn’t exist.

The good news? It’s easy to understand and fix once you know what’s going on. In this post, we’ll walk through what causes this error and how to resolve it step by step.

What Causes This Error?

Here are a few common causes:

1. Accessing a Non-Existent Index

Trying to access an index that’s outside the range of the list.

my_list = [10, 20, 30]
print(my_list[3])  # Error: index 3 does not exist

2. Using a Fixed Index in a Loop

Looping through a list incorrectly using a range that goes too far.

my_list = [1, 2, 3]
for i in range(4):
    print(my_list[i])  # Error on the last iteration

3. Modifying the List Inside a Loop

Removing items from a list while iterating through it.

my_list = [1, 2, 3]
for i in range(len(my_list)):
    my_list.pop()  # List shrinks while loop index grows

4. Off-by-One Errors

Starting from 1 instead of 0 or going one step too far.

my_list = ['a', 'b', 'c']
print(my_list[len(my_list)])  # Error: index is too high

How to Fix It

Fix 1: Check Your Index

Always ensure the index is within the list’s range.

my_list = [10, 20, 30]
if 2 < len(my_list):
    print(my_list[2])

Why it works: This checks if the index exists before accessing it.

Fix 2: Use for item in list Instead of Indexes

Iterate directly over items.

my_list = [1, 2, 3]
for item in my_list:
    print(item)

Why it works: This avoids managing index positions altogether.

Fix 3: Adjust Range in Loops

Make sure your loop range matches the list length.

for i in range(len(my_list)):
    print(my_list[i])

Why it works: This ensures the index never exceeds the list size.

Fix 4: Use Try/Except for Safety

Catch the error to avoid crashes.

try:
    print(my_list[5])
except IndexError:
    print("Index out of range")

Why it works: Gracefully handles the error if it happens.

Real Example

Problem Code

names = ['Alice', 'Bob', 'Charlie']
print("Fourth name is:", names[3])

Output: IndexError: list index out of range

Corrected Version

names = ['Alice', 'Bob', 'Charlie']
if len(names) > 3:
    print("Fourth name is:", names[3])
else:
    print("There are only", len(names), "names.")

Tips to Prevent This Error

  • Always check the length of your list before accessing by index.
  • Use for item in list whenever possible to avoid indexing entirely.
  • Add safety with try/except blocks if list size is uncertain.

 

You may also like