Python IndexError: list index out of range
A plain-words explanation of this Python message: what it means, the usual causes, and the steps that fix it.
The messageIndexError: list index out of range
Make the error yourself
Run with Python 3.14.10. This is the smallest example we could find that shows it.
Python program (main.py)
fruits = ["apple", "banana", "cherry"]
for i in range(4):
print(fruits[i])Output (the real message)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(fruits[i])
~~~~~~^^^
IndexError: list index out of rangeWhy it happens
A list with three items has the positions 0, 1 and 2. Asking for position 3, or any position larger than the last one, fails. The loop in the example counts to 3 but the list stops at 2. The same error appears when the list is empty and you ask for items[0], and when you use a number from user input as a position.
Counting from zero is the usual source of the mistake: the last position is len(items) - 1.
How to fix it
- Loop over the items themselves (
for fruit in fruits) instead of counting positions. - If you need positions, use
range(len(fruits))orenumerate(fruits). - Before using
items[0], check that the list is not empty:if items:. - For the last item write
items[-1], which works on any non-empty list.
The corrected version
Python program (main.py)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output (the corrected version)
apple
banana
cherryHow to avoid it
Prefer loops over items. When you must use positions, print len(items) while you debug.
Questions
Does the same error happen with strings and tuples?
Yes: "abc"[5] gives "string index out of range" and a tuple gives "tuple index out of range".
This is an independent guide. It is not connected with Python, Microsoft, Google, GitHub or the Git project. Product names belong to their owners. Examples were run on 13 November 2026 in a practice folder or a blank workbook; your version may word a message slightly differently.