Python: IndexError: list index out of range
Python throws 'list index out of range' — you asked for an item that isn't there. Usually it's an off-by-one, an empty list, or a hard-coded position. Here's how to find and fix each.
Python stops with:
IndexError: list index out of range
This one is refreshingly literal: you asked a list for an item at a position it doesn't have. A list of 3 items has positions 0, 1, 2 — ask for [3] and there's nothing there, so Python raises rather than guess. The fix is almost always one of three small mistakes.
Cause 1: Off-by-one (the classic)
Indexing starts at 0, so the last valid index of a list of length n is n - 1, not n. Reaching for list[len(list)] is always one too far:
items = ['a', 'b', 'c']
items[3] # IndexError — valid indexes are 0, 1, 2
items[-1] # 'c' ← the safe way to get the last item
Cause 2: The list is empty
If the list has nothing in it, every index is out of range — including [0]. This bites when data didn't load, a filter removed everything, or a file was blank:
results = [r for r in data if r.active]
first = results[0] # IndexError if nothing was active
Cause 3: A hard-coded position that isn't guaranteed
Splitting a line and grabbing parts[1] assumes there's always a second piece. A malformed row breaks it:
name, age = line.split(',') # blows up if a line has no comma
The error is telling the exact truth: that slot doesn't exist. Don't reach for a position without knowing the list is long enough to have it.
The fixes
Check length or use safe access before indexing:
if items: # not empty
print(items[0])
if len(parts) >= 2: # enough pieces
print(parts[1])
last = items[-1] if items else None # safe "last item"
And when you just want to walk everything, loop instead of indexing by number:
for item in items: # no index math, no IndexError
print(item)
The checklist
- You asked for a position the list doesn't have — indexes are
0..len-1. - Off-by-one? Use
[-1]for the last item. - Might be empty? Guard with
if items:before[0]. - Prefer
for item in items:over indexing by number where you can.
Stop reading, start building
This pairs with a hands-on BytExplorer course — do it on your own machine and actually keep the skill.