IndexError
PythonERRORNotableRuntime ErrorHIGH confidence

Sequence index out of range

What this means

Raised when you try to access an index in a sequence (like a list, tuple, or string) that does not exist. This typically happens when the index is greater than or equal to the length of the sequence.

Why it happens
  1. 1Accessing an index equal to the length of the list (e.g., `my_list[len(my_list)]`).
  2. 2Using a negative index that is too large in magnitude for the sequence's length.
  3. 3Trying to access an element in an empty sequence.
How to reproduce

This error is triggered when trying to access the 4th element (at index 3) of a list that only has 3 elements (at indices 0, 1, 2).

trigger — this will error
trigger — this will error
my_list = [10, 20, 30]
print(my_list[3])

expected output

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

Fix 1

Check the length of the sequence before access

WHEN When the index is dynamic or comes from an external source.

Check the length of the sequence before access
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.")

Why this works

By comparing the index against the sequence's length, you can prevent any attempt to access an invalid position.

Fix 2

Iterate over elements directly

WHEN When you need to process every item in a sequence. This is the most Pythonic approach.

Iterate over elements directly
my_list = [10, 20, 30]
# Instead of managing indices, loop over the items directly
for item in my_list:
    print(item)

Why this works

A `for` loop that iterates directly over the sequence is simpler, more readable, and automatically handles stopping after the last element, eliminating the risk of `IndexError`.

Code examples
Triggerpython
lst = [1, 2, 3]
val = lst[10]  # IndexError: list index out of range
Handle with try/exceptpython
try:
    val = lst[index]
except IndexError:
    print(f"Index {index} out of range")
    val = None
Avoid with bounds checkpython
val = lst[index] if 0 <= index < len(lst) else None
What not to do

Wrapping every index access in a `try/except IndexError` block

This is often a sign of poor logic (e.g., an off-by-one error). It's better to fix the root cause of the invalid index instead of just silencing the error.

Sources
Official documentation ↗

cpython/Objects/listobject.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors