IndexError
IndexError: list index out of range
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(fruits[5])
IndexError: list index out of rangeWhat causes this error
An integer index was used that is beyond the bounds of the sequence. For a list of length n, valid indices are -n to n-1. Accessing any index outside this range raises IndexError.
How to fix it
Check the length of the sequence before accessing by index. Use `len()` to verify bounds. Prefer iteration with `for item in sequence` over manual indexing. Use `try/except IndexError` for edge cases.
Code that causes this error
fruits = ["apple", "banana", "cherry"] print(fruits[5])
Fixed code
fruits = ["apple", "banana", "cherry"]
if len(fruits) > 5:
print(fruits[5])
else:
print("Index out of range")About IndexError
An IndexError is raised when you try to access an element at an index that is outside the valid range for a sequence (list, tuple, string). Python sequences are zero-indexed, so a list with 5 elements has valid indices 0 through 4 (and -1 through -5 for negative indexing). Attempting to access index 5 or -6 would raise an IndexError.
This error commonly appears in loops that use manual index tracking, when processing data with fewer elements than expected, and when using hardcoded indices on dynamic data. Unlike KeyError (which applies to dictionaries), IndexError is specific to sequences. Using Pythonic iteration patterns like `for item in list` instead of `for i in range(len(list))` avoids most IndexErrors, and bounds checking before access handles the remaining cases.
Common scenarios
Accessing list elements beyond the list's actual length
Off-by-one errors in loop index calculations
Processing data with fewer elements than expected
Using hardcoded indices on dynamically-sized collections