How do I fix IndexError: list index out of range in Python?
Why the error happens
Python lists are zero-indexed, so valid indices for a list of length n are 0 through n-1. If you use an index equal to or greater than n, or less than -n, Python raises IndexError: list index out of range.
This often occurs when you assume a list has more elements than it does, or when you use an index from another source (like user input) without validation.
How to fix it
First, check the length of the list with len(). If you're using a fixed index, make sure it's within range. If you're iterating, use a for loop over the list directly instead of indexing.
If you need to access elements by index, add a condition to check the index before accessing. For example: if i < len(my_list): ... You can also use try/except to handle the error gracefully.
- Use for item in my_list: instead of for i in range(len(my_list)): when possible.
- Use enumerate() if you need both index and value.
- Check len(my_list) before accessing an index.
- Use slicing (e.g., my_list[2:5]) which won't raise IndexError if the slice is out of bounds.
- Consider using a dictionary or a different data structure if you need sparse indexing.
Common scenarios
If you're modifying a list while iterating, the length can change unexpectedly. Avoid removing items from a list while looping over it; iterate over a copy instead.
If you're reading from a file or user input, validate that the data has enough elements before accessing specific indices.
Common mistakes
- Forgetting that Python indices start at 0, so the last element is at index len(list)-1.
- Assuming a list has a certain number of elements without checking len().
- Using negative indices incorrectly — -1 is the last element, but -len(list)-1 is out of range.
