/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
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
| Situation | Fix |
|---|---|
Index equals len(items) | Use len(items) - 1 as the highest index. |
| Empty list | Test if items: before reading items[0]. |
range(len(items) + 1) loop | Use range(len(items)) or loop over items. |
| Removing items while iterating | Build a new list instead of changing the one you loop. |
items = [1, 2, 3]
for index, value in enumerate(items):
print(index, value)
last = items[-1] if items else NoneSlices never raise this error: items[5:] returns an empty list when the list is shorter. Only reading a single index does.
Sources
Related pages
errors · pythonKeyError: 'key' in PythonPython raises KeyError when you read a dict key that does not exist. Check the key with in, read it with dict.get(key, default), or fix the spelling or type.errors · pythonTypeError: 'NoneType' object is not subscriptablePython raises this TypeError when you index a value that is None, often the result of list.sort(), dict.get() or re.match(). Find where None comes from.errors · pythonValueError: invalid literal for int() with base 10Python raises ValueError: invalid literal for int() with base 10 when text is not a whole number: '3.5', '' or '1,000'. Clean the string, or use float() first.