IndexError: list index out of range, occurs when we try to access a list element using an index that does not exist. This usually happens when the index is greater than the last valid position or smaller than the allowed negative index range.
a = [1, 2, 3]
print(a[3])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
IndexError: list index out of range
Explanation: list contains three elements with valid indexes 0, 1 and 2. Accessing a[3] raises an IndexError because that position does not exist.
Common Causes of IndexError
1. Accessing an Index Beyond the List Length: Trying to access a position greater than the last valid index raises an error.
a = [1, 2, 3]
print(a[5])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
IndexError: list index out of range
Explanation: list has only three elements, so index 5 does not exist.
2. Using an Invalid Negative Index: Negative indexes access elements from the end of the list. An index beyond the allowed range raises an error.
a = [1, 2, 3]
print(a[-4])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
IndexError: list index out of range
Explanation: list length is 3, so valid negative indexes are -1, -2 and -3. Index -4 is outside the valid range.
3. Incorrect Loop Iteration: Using an incorrect range while iterating through a list can lead to invalid index access.
a = [1, 2, 3]
for i in range(len(a) + 1):
print(a[i])
Output
1
2
3
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
IndexError: list index out of range
Explanation: range(len(a) + 1) generates values 0, 1, 2, 3. When i becomes 3, a[3] causes an IndexError.
Handling IndexError
1. Check the List Length Before Accessing: Before accessing an index, verify that it exists in the list.
a = [10, 20, 30]
idx = 2
if idx < len(a):
print(a[idx])
else:
print("Index out of range")
Output
30
Explanation: idx < len(a) ensures the index is valid before accessing a[idx].
2. Use Negative Indexes Carefully: Make sure the negative index falls within the valid range.
a = [10, 20, 30]
try:
print(a[-1])
print(a[-4])
except IndexError:
print("Negative index is out of range.")
Output
30 Negative index is out of range.
Explanation: a[-1] accesses the last element, while a[-4] raises an IndexError because it exceeds the valid negative range.
3. Iterate Using the Correct Range: Use range(len(list)) when iterating with indexes.
a = [10, 20, 30]
for i in range(len(a)):
print(a[i])
Output
10 20 30
Explanation: range(len(a)) generates only valid indexes for the list.
4. Use enumerate() for Safer Iteration: enumerate() provides both index and value without manually managing indexes.
a = [10, 20, 30]
for idx, val in enumerate(a):
print(f"Index: {idx}, Value: {val}")
Output
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30
Explanation: enumerate(a) automatically returns valid indexes and their corresponding values.
5. Using try-except: A try-except block prevents the program from terminating unexpectedly.
a = [10, 20, 30]
idx = 3
try:
print(a[idx])
except IndexError:
print("Index is out of range. Please check your list.")
Output
Index is out of range. Please check your list.
Explanation: If a[idx] raises an IndexError, the except block handles the error and displays a custom message.
Best Practices to Avoid IndexError
- Check list length before accessing indexes.
- Use valid positive and negative indexes.
- Prefer enumerate() when iterating through lists.
- Use try-except blocks when index values may be uncertain.
- Avoid using ranges that exceed the list size.
Following these practices helps prevent IndexError and makes list operations safer and more reliable.