The error message:
IndexError: index out of bounds
occurs when you try to access an index that is outside the valid range of a sequence (such as a list, tuple, or string).
1. Causes and Solutions
Cause 1: Accessing an Index That Doesn’t Exist
If an index is greater than or equal to the length of a sequence, Python raises an IndexError
.
Incorrect Code:
my_list = [1, 2, 3]
print(my_list[5]) # Error: Index 5 does not exist
Solution: Check if the index is valid before accessing it.
index = 5
if 0 <= index < len(my_list):
print(my_list[index])
else:
print("Index out of bounds")
Cause 2: Using Negative Indices That Exceed the Valid Range
Negative indices count from the end (-1 is the last element), but if they exceed the sequence length, an error occurs.
Incorrect Code:
my_list = [10, 20, 30]
print(my_list[-4]) # Error: Only -1, -2, -3 are valid
Solution: Ensure the negative index is within range.
index = -4
if -len(my_list) <= index < len(my_list):
print(my_list[index])
else:
print("Negative index out of bounds")
Cause 3: Iterating Beyond the Length of a Sequence
If you use a for
loop with an incorrect range, it may exceed the list’s length.
Incorrect Code:
my_list = [5, 10, 15]
for i in range(5): # Error: 5 exceeds valid indices (0,1,2)
print(my_list[i])
Solution: Use len()
to limit iteration.
for i in range(len(my_list)): # Stops at the last valid index
print(my_list[i])
Cause 4: Using .pop()
on an Empty List
The .pop()
method removes an element by index, but calling it on an empty list or with an invalid index raises an error.
Incorrect Code:
my_list = []
my_list.pop() # Error: Cannot pop from an empty list
Solution: Check if the list is non-empty before using .pop()
.
if my_list:
my_list.pop()
else:
print("List is empty, cannot pop")
Cause 5: Out-of-Bounds Indexing in NumPy Arrays
NumPy arrays have strict bounds checking, so exceeding their length raises an IndexError
.
Incorrect Code:
import numpy as np
arr = np.array([1, 2, 3])
print(arr[10]) # Error: Index out of bounds
Solution: Validate the index before accessing it.
index = 10
if 0 <= index < arr.size:
print(arr[index])
else:
print("Index out of bounds")