ProjectStack
python

IndexError: list index out of range

You tried to access a list position (index) that doesn't exist. If a list has 3 items, valid indices are 0, 1, and 2 — accessing index 3 or higher raises IndexError.

Common causes

  • Using a hardcoded index that's larger than the list actually is
  • The list is shorter than expected — it might even be empty
  • An off-by-one error: iterating from 1 to len(list) instead of 0 to len(list)-1
  • Modifying the list size during iteration causes the length to shrink mid-loop

How to fix it

  1. Check the list length before accessing: if len(items) > index: print(items[index])
  2. Print the list and its length to understand what's in it: print(items, len(items))
  3. Use a for item in list: loop instead of manual indexing to avoid out-of-range issues
  4. Use negative indexing to access the last item: items[-1] instead of items[len(items)]

Example

Traceback (most recent call last): File "app.py", line 3, in <module> print(names[5]) IndexError: list index out of range

Accessing index 5 on a list that only has 3 elements

Have a different error?

Paste any error message into the Error Translator to get an instant explanation.