Sequence index out of range
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.
- 1Accessing an index equal to the length of the list (e.g., `my_list[len(my_list)]`).
- 2Using a negative index that is too large in magnitude for the sequence's length.
- 3Trying to access an element in an empty sequence.
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).
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.
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.
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`.
lst = [1, 2, 3] val = lst[10] # IndexError: list index out of range
try:
val = lst[index]
except IndexError:
print(f"Index {index} out of range")
val = Noneval = lst[index] if 0 <= index < len(lst) else None
✕ 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.
cpython/Objects/listobject.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev