IndexError, what it means and how to fix it

Sequences in Python are indexed from zero, and asking for a position at or beyond the length raises IndexError. The message does not tell you which index was requested or how long the list was, which is why this error is debugged by printing both. The causes are a short list of regulars: counting from one, an empty result nobody checked, or data that arrived shorter than the code assumed.

What it looks like

items = ["a", "b", "c"]
print(items[3])          # valid indexes are 0, 1, 2

Traceback (most recent call last):
  File "main.py", line 2, in <module>
IndexError: list index out of range

# fixed: stay inside len(items), or guard first
if len(items) > 3:
    print(items[3])

The fix, in order

  1. Print len(seq) and the index at the failing line. Nine times out of ten the two numbers explain everything: the index is exactly the length (the classic off-by-one), or the length is zero (an empty result).
  2. Remember the last valid index is len(seq) - 1. Loops written as for i in range(len(items) + 1) or manual counting from 1 produce the out-of-range index; prefer for item in items or enumerate(items) and skip indexes entirely.
  3. Check for the empty case where data is loaded. Filters, queries, file reads, and splits of empty text can all return empty sequences. Guard with if items: before taking items[0].
  4. Prefer slicing when “up to N” is acceptable. Slices never raise: items[:5] quietly returns what exists. Indexing is a demand; slicing is a request.
  5. Pop defensively only when absence is normal: items.pop() on an empty list raises the same error; check length, or restructure so emptiness is handled as its own case.

If it still happens

If lengths look right in your prints but the error persists, the sequence at the failing line is a different object than the one printed (reassigned between the print and the access, or a second variable with a similar name). Print both in the same statement, immediately before the failing line.

Common questions

What is the difference between IndexError and KeyError? Same idea, different container: IndexError is a position that does not exist in a sequence (list, tuple, string); KeyError is a missing key in a dictionary. The fix in both cases is reconciling what the code expects with what the container actually holds.

Do negative indexes count as out of range? Negative indexes count from the end (-1 is the last element) and are legal down to -len(seq). Asking for -4 in a 3-item list raises IndexError just as asking for 3 does.

Related errors

KeyError · TypeError: 'NoneType' object is not subscriptable · StopIteration