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
- Check the list length before accessing: if len(items) > index: print(items[index])
- Print the list and its length to understand what's in it: print(items, len(items))
- Use a for item in list: loop instead of manual indexing to avoid out-of-range issues
- 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 rangeAccessing 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.
