IndexError: list index out of range
Most likely cause: Code assumes a list has more items than it actually contains at the moment of access, such as using an index that is too high.
Try first: Locate the exact line
Likely causes
- Code assumes a list has more items than it actually contains at the moment of access, such as using an index that is too high.most likely
- The list was not populated or was emptied before the line that caused the error ran.possible
- A loop or calculation produced an index value outside the valid range for the current list size.possible
How to fix it
Locate the exact lineSafe
Open the source file and find the line number shown in the error traceback, then look at how the list is being indexed there.
Check list length before accessSafe
Add a temporary print statement right before the failing line to show the current length of the list and its contents.
print(len(your_list), your_list)Add a length checkChanges settings
Wrap the access in an if statement that only runs if the index is less than the list length.
if index < len(your_list): ...
If that didn't fix it
Add print statements showing the list size and the attempted index value right before the error line, then rerun the code.
When to see a technician
If this error appears inside a larger application you did not write, ask the original developer to review the list-handling logic.
Quick answers
- What does IndexError: list index out of range mean?
- This error occurs in programming when code tries to read or change an item in a list by its position number, but that position does not exist because the list is shorter than expected.
- What causes IndexError: list index out of range?
- Code assumes a list has more items than it actually contains at the moment of access, such as using an index that is too high. (most likely) The list was not populated or was emptied before the line that caused the error ran. (possible) A loop or calculation produced an index value outside the valid range for the current list size. (possible)
- How do I fix IndexError: list index out of range?
- Try these in order, safest first: 1. Locate the exact line. 2. Check list length before access. 3. Add a length check.
- What if that didn't fix it?
- Add print statements showing the list size and the attempted index value right before the error line, then rerun the code.
- When should I see a technician?
- If this error appears inside a larger application you did not write, ask the original developer to review the list-handling logic.