← Debugging Guides

阅读中文版本

Python IndexError — List Index Out of Range

Fix IndexError list index out of range by checking length before indexing, using at most len-1, and preferring iteration or slicing.

beginnerdebuggingpythonindexerrorboundary

Symptoms

  • Python raises "IndexError: list index out of range"
  • The error appears only when the list is empty or shorter than expected
  • Code that assumes the first element fails on an empty API response

Possible causes

  • The collection is empty and code accesses element 0
  • An off-by-one loop uses <= len instead of < len
  • Split or parse produced fewer items than the code assumes

Diagnosis steps

Check the length at the failing point

print(len(items), repr(items))

Interpretation

Knowing the actual length explains which index is invalid and whether the source returned empty.

Find the off-by-one

grep -n "range(len\|\[i\]\|\[0\]" app.py

Interpretation

Audit index expressions and ranges; range(len(x)) is safe, <= len(x) is not.

Root cause

Python lists are zero-indexed and validate the index at access time. IndexError is raised whenever the index is negative beyond the list length or greater than or equal to len(list).

Fix

Test for non-empty before indexing the first element, iterate directly instead of by index, use range(len(x)) (not <=), and prefer slicing or enumerate for safety.

Risk note

Silently padding a list with a placeholder can mask a genuinely empty response; log the empty case explicitly.

Verify the fix

Rerun with an empty and a single-element input; both should complete without IndexError. Add tests for the empty case.

Symptoms

When you hit “Python IndexError — List Index Out of Range”, guessing wastes time. The guide below follows evidence: reproduce the symptom, run targeted diagnostics, identify the root cause, apply the fix, and verify it with concrete checks.

Observed symptoms include:

  • Python raises “IndexError: list index out of range”
  • The error appears only when the list is empty or shorter than expected
  • Code that assumes the first element fails on an empty API response

Reproduce and Diagnose

Reproduce the failure in isolation before changing any code. Work through the checks below in order; each one narrows the search space.

Step 1: Check the length at the failing point

print(len(items), repr(items))

Knowing the actual length explains which index is invalid and whether the source returned empty.

Step 2: Find the off-by-one

grep -n "range(len\|\[i\]\|\[0\]" app.py

Audit index expressions and ranges; range(len(x)) is safe, <= len(x) is not.

Likely contributors, in order of frequency:

  • The collection is empty and code accesses element 0
  • An off-by-one loop uses <= len instead of < len
  • Split or parse produced fewer items than the code assumes

Root Cause

Python lists are zero-indexed and validate the index at access time. IndexError is raised whenever the index is negative beyond the list length or greater than or equal to len(list).

The Fix

Test for non-empty before indexing the first element, iterate directly instead of by index, use range(len(x)) (not <=), and prefer slicing or enumerate for safety.

Watch out: Silently padding a list with a placeholder can mask a genuinely empty response; log the empty case explicitly.

items = []
# print(items[0])   # IndexError: list index out of range

first = items[0] if items else None
for i in range(len(items)):    # safe: 0..len-1
    process(items[i])

# prefer direct iteration
for item in items:
    process(item)

Verify and Prevent

Rerun with an empty and a single-element input; both should complete without IndexError. Add tests for the empty case.

Once verified, add a regression test that reproduces the original symptom so the failure cannot silently return.

This class of failure is usually environmental rather than pure logic, so capture the exact command, the environment variables, and the working directory in your bug report. Reproduce it in the smallest possible script, then widen the scope only once the minimal case is understood. A short written checklist for this failure mode saves hours the next time it appears.