Error guide · IndexError
IndexError: list index out of range
You asked for a position in a list (or string) that does not exist.
Example
marks = [72, 85, 90] print(marks[3])
What Python says
IndexError: list index out of range
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Indexes start at 0, so a list of 3 items has positions 0, 1 and 2. Position 3 is past the end. This often happens in loops that go one step too far.
How to fix it
marks = [72, 85, 90] print(marks[2])
Output: 90
Tips
- The last item is at
len(items) - 1, or simplyitems[-1]. - Loop over the items directly (
for m in marks:) instead of by position. - With
range(len(items)), never add 1 to the stop value. - An empty list has no items at all, so even
items[0]fails.