Home › Errors › IndexError

Python IndexError: list index out of range

Exception: IndexErrorCategory: sequence lookupRaised at: runtime

What this error means

Code asked a sequence — list, tuple, or string — for a position that does not exist. Python indexes from zero, so a list of n items accepts positive indexes 0 through n − 1. The single most important fact on this page: len(items) is a count, not a position. items[len(items)] is out of range on every list ever created.

Note what does not raise IndexError: slices. items[5:99] on a three-item list quietly returns what exists (nothing, here). Only single-position lookups crash — which is why an IndexError always points at an expression with one number inside the brackets.

A real example

colors = ["red", "green", "blue"]
print(colors[3])   # "the 3rd color"... but Python counts from 0
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(colors[3])
          ~~~~~~^^^
IndexError: list index out of range

The third color as a human counts is colors[2]. The last item, always safely, is colors[-1].

Why it happens

How to debug it

  1. Print len(items) and the failing index right before the crash line — the comparison is the diagnosis.
  2. If the index comes from a loop, hand-run only the final iteration; boundary bugs live there.
  3. If the index is a constant, decide whether it encodes human counting (subtract one) or "the last item" (use -1).
  4. If the list can legitimately be empty, guard first: if items: — do not catch IndexError to paper over missing data.

Fix it interactively

Five free problems, each a different real-world shape of this exact error:

Practice more Python bugs →
🇮🇳 Hindi में समझें

List से ऐसी position माँगी जो है ही नहीं। Python 0 से गिनता है — 3 items वाली list में positions 0, 1, 2 हैं; position 3 exist नहीं करती। आखिरी item चाहिए तो list[-1] लिखो, और loop में range(len(list)) से आगे मत जाओ। len() गिनती बताता है, position नहीं!

पूरी Hindi explanation पढ़ें →

Related errors

String slicing never raises but silently truncates — see off-by-one in string slicing and the full errors guide.