Skip to main content

Fix IndexError in Python

Error Reference

IndexError: list index out of range

You accessed a position that doesn't exist. Here's how to avoid it.

Prevention

  • Check length before accessing: if index < len(items): ...
  • Use slicing or .get() (for dicts) to avoid direct indexing when optional.
  • Prefer for item in items loops instead of manual indexes when possible.

Example fix

for i in range(len(users)):
print(users[i]) # IndexError when users is empty

# Better:
for user in users:
print(user)

Next up in your learning path