IndexPython Error

IndexError

IndexError: list index out of range

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(data[5])
IndexError: list index out of range

What causes this error

A list was accessed with an integer index that is beyond its valid range (0 to len-1 for positive, -1 to -len for negative).

How to fix it

Check `len(list)` before accessing by index. Use `for item in list` instead of index-based access. Use try/except IndexError. Consider using .get()-style patterns or conditional expressions.

Code that causes this error

Broken
data = [10, 20, 30]
print(data[5])

Fixed code

Fixed
data = [10, 20, 30]
idx = 5
if idx < len(data):
    print(data[idx])
else:
    print(f"Index {idx} out of range for list of length {len(data)}")

About IndexError

This is the most common form of IndexError, occurring when you access a list element at an index that exceeds the list's bounds. For a list of length n, valid indices are 0 to n-1 (positive) and -1 to -n (negative). Any index outside this range raises this error.

It commonly appears in loops with manual index management, when processing data with fewer elements than expected, when using hardcoded indices on dynamic data, and in off-by-one errors. The fix depends on the context: check bounds before accessing, use try/except, iterate directly over the list instead of using indices, or use Python's EAFP (Easier to Ask Forgiveness than Permission) pattern. The list's `.pop()` method also raises IndexError when called on an empty list.

Common scenarios

1

Accessing list elements beyond the list's actual length

2

Off-by-one errors in loop index calculations

3

Processing data with fewer elements than expected

4

Using hardcoded indices on dynamically-sized collections

Related errors