The error message:
IndexError: list index out of range
occurs when you try to access an index in a list that does not exist. This means the index is either negative beyond range or larger than the last available index.
1. Causes and Solutions
Cause 1: Accessing an Index That Does Not Exist
If you try to access an index that is greater than or equal to the list’s length, Python raises an IndexError
.
Incorrect Code:
numbers = [10, 20, 30]
print(numbers[3]) # Error: Index 3 is out of range (valid indices: 0, 1, 2)
Solution: Ensure the index is within the list length.
if len(numbers) > 3:
print(numbers[3])
else:
print("Index is out of range")
Cause 2: Using a Loop with an Incorrect Range
If you loop beyond the valid indices, you may get this error.
Incorrect Code:
numbers = [1, 2, 3]
for i in range(4): # Error: range(4) includes index 3, which does not exist
print(numbers[i])
Solution: Use len(numbers)
to avoid out-of-range errors.
for i in range(len(numbers)): # Safe iteration
print(numbers[i])
Or use a direct iteration approach.
for num in numbers:
print(num)
Cause 3: Negative Index Beyond List Range
Negative indices refer to elements from the end, but if they exceed the list size, an error occurs.
Incorrect Code:
numbers = [10, 20, 30]
print(numbers[-4]) # Error: Only -1, -2, and -3 are valid
Solution: Ensure the negative index is within range.
if -4 >= -len(numbers):
print(numbers[-4])
else:
print("Negative index out of range")
Cause 4: Modifying a List While Iterating
If you remove items while iterating with an index, the list size changes, causing an out-of-range error.
Incorrect Code:
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
numbers.pop(i) # Error: List size changes, causing an invalid index
Solution: Iterate over a copy or use list comprehension.
numbers = [1, 2, 3, 4]
for num in numbers[:]: # Iterating over a copy prevents index issues
numbers.remove(num)
print(numbers)
Cause 5: Using an Index Without Checking List Length
Functions that return lists (like split()
, findall()
, etc.) may return an empty list, leading to an out-of-range error.
Incorrect Code:
words = "Hello".split(",") # ['Hello'], no comma found
print(words[1]) # Error: Only one element exists at index 0
Solution: Check if the list has enough elements before accessing.
if len(words) > 1:
print(words[1])
else:
print("Not enough elements in the list")