Skip to content

/errors/python/indexerror-list-index-out-of-range

IndexError: list index out of range in Python

verified onenvironmentlocal · linux 6.18.44-fc-v140 x64 · GNU bash 5.2.21 · Python 3.11.17updated
tool
Python
exit code
1
versions
Python 3.x
os
any

IndexError: list index out of range means the code read items[i] and the list has no item at position i. Python counts from 0, so a list of three items accepts the indexes 0, 1 and 2 (and -1 to -3 from the end). Check len(items) against the index, or loop over the items directly.

Reproduce it

bash
cat > app.py <<'EOF2'
items = [1, 2, 3]
print(items[3])
EOF2
python3 app.py 2>&1 | tail -n 1
exit ${PIPESTATUS[0]}

Output · exit 1

IndexError: list index out of range

The last line of the traceback names the exception and the message. The lines above it show the file and the line that raised it.

Causes and fixes

SituationFix
Index equals len(items)Use len(items) - 1 as the highest index.
Empty listTest if items: before reading items[0].
range(len(items) + 1) loopUse range(len(items)) or loop over items.
Removing items while iteratingBuild a new list instead of changing the one you loop.
python
items = [1, 2, 3]
for index, value in enumerate(items):
    print(index, value)

last = items[-1] if items else None

Slices never raise this error: items[5:] returns an empty list when the list is shorter. Only reading a single index does.

Sources