IndexError: list index out of range
Updated
The Python error "list index out of range" means you asked for a position the list does not have. Valid indexes run from 0 to len - 1. The usual causes, and the fix.
What you see
names = ["ada", "grace", "linus"]
print(names[3])Traceback (most recent call last):
File "/home/me/project/main.py", line 2, in <module>
print(names[3])
~~~~~^^^
IndexError: list index out of rangeWhat it means
A list of three items has positions 0, 1 and 2. Position 3 does not exist. Negative indexes count from the end, so -1 to -3 are valid here and -4 is not.
Strings and tuples give the same error with their own name: "string index out of range", "tuple index out of range".
Why it happens
- Counting from 1.
names[len(names)]is one past the end; the last item isnames[len(names) - 1], or simplynames[-1]. - A loop that goes one too far, such as
for i in range(len(names) + 1). - An empty list.
results[0]fails when the search found nothing. - A command-line argument that was not given.
sys.argv[1]fails when the script runs with no arguments. - Removing items from a list while looping over its indexes, so the list gets shorter than the range.
How to fix it
Loop over the items, not over numbers, and there is no index to get wrong:
for name in names:
print(name)
for i, name in enumerate(names): # when you need the position too
print(i, name)
Check before taking the first or last item of a list that may be empty:
if results:
first = results[0]
For arguments, use argparse, which prints a usage message instead of an IndexError.
How each Python version words it
| Python | Prints |
|---|---|
| 3.9–3.15 | IndexError: list index out of range |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on October 25, 2026.
The wording is the same in every version here.
Questions
Why does slicing not raise this?
Slices are clipped to the list: names[3:10] is [] and names[1:10] is everything from position 1. Only a single index has to exist.
Why does it work in one run and fail in another?
The list length depends on the data. Print len(names) before the failing line; it is usually 0.
Sources
- Sequence types: common operations, Python documentation
- Built-in functions:
enumerate(), Python documentation - argparse, Python documentation
Read on October 25, 2026.