PROGRAMMING

Python List Index Out of Range: Causes and Fixes

Learn why Python raises IndexError: list index out of range, with practical examples, common mistakes, debugging steps, and safer ways to access list items.

Student learning resource7 min read

The Python error IndexError: list index out of range occurs when code tries to access a list position that does not exist. It often happens when a loop goes one step too far, a list is empty, or an index is calculated incorrectly. This guide explains how to identify the cause and fix it without hiding the underlying bug.

What does list index out of range mean?

Python lists use zero-based indexing. In a list containing three items, the valid indexes are 0, 1, and 2. Trying to access index 3 raises an IndexError because there is no fourth item.

The valid index range for a non-empty list is 0 through len(list_name) - 1. An empty list has no valid element indexes.

fruits = ["apple", "banana", "orange"]

print(fruits[0])  # apple
print(fruits[2])  # orange
print(fruits[3])  # IndexError

1. Looping one step too far

A common cause is using range(len(items) + 1). The extra step produces an index equal to the list length, which is outside the valid range.

Use range(len(items)) when an index is genuinely needed, or iterate over the items directly when you only need their values.

numbers = [10, 20, 30]

# Incorrect: attempts to access numbers[3]
for i in range(len(numbers) + 1):
    print(numbers[i])

# Correct: visit each item
for number in numbers:
    print(number)

2. Accessing an empty list

A list can be empty because it was initialized without values, filtered to zero results, or populated only under a condition that was not met. Accessing items[0] in that situation raises IndexError.

Check whether the list contains an item before accessing its first element. If an empty result is unexpected, investigate why the list was not populated.

results = []

if results:
    print(results[0])
else:
    print("No results were found.")

3. Confusing list length with the last index

The length of a list is the number of items, not the last valid index. For example, a list of five items has length 5 but its final index is 4.

Use len(items) - 1 only when the list is non-empty and you specifically need the last index. Python also supports negative indexing, such as items[-1], but the list must not be empty.

items = ["A", "B", "C"]

print(len(items))      # 3
print(len(items) - 1)  # 2
print(items[-1])       # C

4. Modifying a list while iterating

Removing or inserting items while looping over a list can shift positions and cause unexpected behavior. The list itself may be changing during the loop.

When filtering items, consider building a new list instead of removing elements from the same list while iterating over it.

numbers = [1, 2, 3, 4, 5]

evens = [
    number for number in numbers
    if number % 2 == 0
]

print(evens)  # [2, 4]

5. A practical debugging checklist

When the error appears, inspect the exact line named in the traceback. Then check the index value, the current list length, and whether the list changes before that line executes.

  • Read the traceback to confirm the exception.
  • Inspect the index being used.
  • Check len(items) immediately before the failing access.
  • Check whether the list is empty or changes inside a loop.
  • Test boundary cases, including an empty list and a one-item list.
  • Fix the index calculation or control flow instead of catching every IndexError indiscriminately.

6. How to prevent IndexError

Prefer direct iteration when you do not need indexes. When you do need an index, use a range that matches the list length. Validate external input and handle empty results explicitly.

Avoid using try/except as a substitute for correct bounds logic. Exception handling is useful when an exceptional condition is expected, but the program should still have a clear plan for what to do when an item does not exist.

items = ["red", "blue", "green"]
index = 1

if 0 <= index < len(items):
    print(items[index])
else:
    print("Index is outside the valid range.")

Frequently asked questions

Why does Python say list index out of range? Your code is requesting an index that does not exist in the current list.

How do I fix IndexError in a for loop? Check the loop boundaries and remove any extra step beyond the final valid index.

Can an empty list cause IndexError? Yes. An empty list has no valid element indexes.

Is len(my_list) a valid index? No. It is the number of items, so it is one greater than the final valid index for a non-empty list.

Should I use try/except to fix this error? Usually, fix the incorrect index or handle the empty-list case directly. Use exception handling when it fits the expected behavior of your program.

Keep learning Python debugging

Understanding the traceback and checking the values involved will help you diagnose more than list errors. Continue with our [Python Errors Explained: A Practical Debugging Guide](/blog/python-debugging-guide) for a broader debugging workflow.

If you need subject-focused guidance while learning programming concepts, explore [Programming Assignment Help](/services/programming-assignment-help). Use academic support in accordance with your course rules and make sure you understand your own submitted work.

KEEP LEARNING

Understanding the concept is the first step.

Explore related resources or learn about subject-focused tutoring designed to help you understand the material.