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
- The length-as-index trap —
items[len(items)]or a loop that runs tolen(items)inclusively. - Off-by-one loops —
range(len(items) + 1), or a while-loop with<=where<belongs; works on every pass except the last. - Human counting — asking for "item 3" with
[3]when position 3 is the fourth element. - The empty-list edge —
items[0]crashes when a filter, a bad file, or a new user handed you zero elements.
How to debug it
- Print
len(items)and the failing index right before the crash line — the comparison is the diagnosis. - If the index comes from a loop, hand-run only the final iteration; boundary bugs live there.
- If the index is a constant, decide whether it encodes human counting (subtract one) or "the last item" (use
-1). - 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 नहीं!
Related errors
- KeyError — the same missing-lookup story, for dictionaries instead of positions.
- ValueError — raised by list.index(x) when x is absent — a lookup by value, not position.
String slicing never raises but silently truncates — see off-by-one in string slicing and the full errors guide.