python
index_error
ai_generated
true
IndexError: list index out of range
ID: python/indexerror-list-out-of-range
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Accessing a list index that doesn't exist. Common in loops, API responses, and off-by-one errors.
genericWorkarounds
-
92% success Check len() before access or use try/except with clear fallback logic
if idx < len(items): val = items[idx]
Sources: https://docs.python.org/3/library/functions.html#len
-
88% success Use negative indexing or slice notation for safe tail access
last = items[-1] if items else default
Sources: https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
Dead Ends
Common approaches that don't work:
-
Wrap in try/except IndexError
70% fail
Masks the real issue — the list is shorter than expected
-
Pad list with None values
60% fail
Introduces None downstream which causes TypeError later
Error Chain
Preceded by: