|
| Home |
|---|
The IndexError: list index out of range is one of the most common errors beginners encounter when working with Python lists.
This error occurs when a program tries to access an index that does not exist in a list.
Python lists use zero-based indexing. This means the first
element of a list has index 0.
numbers = [10,20,30]
print(numbers[0])
print(numbers[1])
print(numbers[2])
10
20
30
If we try to access an index that does not exist, Python will raise an error.
numbers = [10,20,30]
print(numbers[3])
IndexError: list index out of range
The list contains only three elements with indexes 0, 1, and 2. Index 3 does not exist.
colors = ["red","green","blue"]
print(colors[5])
IndexError: list index out of range
This error commonly occurs when loops exceed the list length.
numbers = [10,20,30]
for i in range(5):
print(numbers[i])
IndexError: list index out of range
Use the len() function to limit the loop range.
numbers = [10,20,30]
for i in range(len(numbers)):
print(numbers[i])
10
20
30
If list elements are removed, the number of indexes changes.
numbers = [10,20,30]
numbers.pop()
print(numbers[2])
IndexError: list index out of range
Trying to access elements in an empty list also causes this error.
numbers = []
print(numbers[0])
IndexError: list index out of range
You can prevent this error by checking the list length before accessing elements.
numbers = [10,20,30]
if len(numbers) > 2:
print(numbers[2])
30
Python allows programs to handle errors using
try and except.
numbers = [10,20,30]
try:
print(numbers[5])
except IndexError:
print("Index does not exist")
Index does not exist
The IndexError: list index out of range occurs when a program tries to access an index that does not exist in a list.
Using correct indexing, loops based on len(),
and error handling techniques can prevent this problem.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net