ShareYourGroupShareYourGroupError Explainer

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 range

Why 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

  1. Loop over the items themselves (for fruit in fruits) instead of counting positions.
  2. If you need positions, use range(len(fruits)) or enumerate(fruits).
  3. Before using items[0], check that the list is not empty: if items:.
  4. 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
cherry

How 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.