Python IndexError: list index out of range
The code tries to access a list index that is beyond the list's length.
Explanation
IndexError occurs when you try to access a list (or other sequence) element at an index that doesn't exist. List indices in Python start at 0, so a list of length 3 has valid indices 0, 1, and 2. Accessing index 3 or higher raises IndexError. This commonly happens when iterating beyond list bounds, when assuming a list has a certain number of elements, or when negative indexing goes beyond the list length.
Common Causes
- Index exceeds list length
- Empty list accessed by index
- Off-by-one error in loops
- Assuming list has certain elements
- Incorrect array index calculation
Solution
Check the list length before accessing by index using len(). Use try-except IndexError blocks for safe access. Use enumerate() for index-based iteration instead of manual index management. Use list slicing which doesn't raise errors for out-of-bounds indices. For empty lists, add a check before accessing the first element. Consider using collections.deque for operations where you need to access elements from both ends.
Code Example
# IndexError from empty list
users = []
first = users[0] # IndexError: list index out of range
# Fix: check length first
if users:
first = users[0]
# IndexError from out of range
items = [1, 2, 3]
fifth = items[4] # IndexError
# Fix: check index
if len(items) > 4:
fifth = items[4]
# Safe access function
def safe_index(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default
result = safe_index(items, 4, 'N/A')
# Using enumerate for iteration (no manual index)
for i, item in enumerate(items):
print(f'{i}: {item}')
# Slicing doesn't raise IndexError
subset = items[0:100] # returns all available items
Error Information
Language
python
Difficulty
Beginner
Views
214
Related Errors
Python
Python RuntimeWarning: coroutine was never awaited
An async coroutine was created but never awaited, so it never executed.
Python
Python ModuleNotFoundError
Python cannot find the specified module in the installed packages or system path.
Python
Python PIL/Pillow Image Not Found
The PIL/Pillow library cannot locate an image file at the specified path.
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.