IndexError: List Index Out of Range in Python
An IndexError: list index out of range occurs in Python when you try to access an item from a list using an index that does not exist. As an example, if a list has only three items, its valid indexes are 0, 1, and 2. Trying to access list[3] or list[-4] will raise this error because Python cannot find an element at that position.
This error is common for beginners and experienced developers because it usually means there is a mismatch between the expected size of a list and the index being used. Understanding how list indexes work, why the error happens, and how to prevent it is essential for writing reliable Python code It's one of those things that adds up..
What Is a Python List?
A Python list is an ordered, mutable collection of values. Lists can store numbers, strings, objects, or even other lists.
Example:
fruits = ["apple", "banana", "cherry"]
In this list:
fruits[0] # "apple"
fruits[1] # "banana"
fruits[2] # "cherry"
Python uses zero-based indexing, which means the first item is stored at index 0, not index 1 Which is the point..
What Does IndexError: list index out of range Mean?
The error message:
IndexError: list index out of range
means that Python tried to access a list position that is outside the valid range of indexes Simple, but easy to overlook..
For example:
numbers = [10, 20, 30]
print(numbers[3])
This code raises an IndexError because numbers has three items, and the valid indexes are 0, 1, and 2.
The error is not saying that the list is empty in every case. It means the specific index you used is not available.
Why Does This Error Happen?
Most IndexError errors happen because of one of the following reasons:
- Accessing an index that is too large
- Accessing an index that is too small
- Using the wrong loop range
- Assuming a list has more items than it actually does
- Using a value from user input as a list index
- Misunderstanding negative indexing
- Working with an empty list
Example 1: Accessing an Index That Is Too Large
This is the most common cause of the error Surprisingly effective..
colors = ["red", "green", "blue"]
print(colors[3])
The list contains three elements, but index 3 does not exist The details matter here..
The correct indexes are:
colors[0] # red
colors[1] # green
colors[2] # blue
To safely access the last item, use:
print(colors[-1])
Negative indexes count from the end of the list.
colors[-1] # blue
colors[-2] # green
colors[-3] # red
On the flip side, be careful with negative indexes too:
colors[-4]
This also raises an IndexError because the list does not have four items.
Example 2: Accessing an Empty List
An empty list has no valid indexes.
items = []
print(items[0])
This raises:
IndexError: list index out of range
To avoid this, check whether the list is empty before accessing an item.
items = []
if items:
print(items[0])
else:
print("The list is empty")
Example 3: Using the Wrong Loop Range
A frequent mistake is using range(len(list) + 1) when looping through a list.
Incorrect example:
names = ["Alice", "Bob", "Charlie"]
for i in range(len(names) + 1):
print(names[i])
This code works for indexes 0, 1, and 2, but then tries to access names[3], which does not exist.
Correct version:
names = ["Alice", "Bob", "Charlie"]
for i in range(len(names)):
print(names[i])
Or, even better, use direct iteration:
for name in names:
print(name)
If you need both the index and the value, use enumerate():
for index, name in enumerate(names):
print(index, name)
Output:
0 Alice
1 Bob
2 Charlie
Example 4: Assuming a List Has More Data Than It Contains
Sometimes the list is not empty, but it has fewer items than expected It's one of those things that adds up..
scores = [88, 92, 76]
print(scores[3])
The code assumes there is a fourth score, but there is no fourth item.
A safer version checks the list length first:
scores = [88, 92, 76]
if len(scores) > 3:
print(scores[3])
else:
print("There are not enough scores")
How to Fix IndexError: list index out of range
1. Check the List Length
Before accessing a specific index, compare it with the list length.
data = ["a", "b", "c"]
index = 2
if 0 <= index < len(data):
print(data[index])
else:
print("Invalid index")
The condition:
0 <= index < len(data)
checks that the index is both non-negative and less than the number of items in the list.
2. Use Safe Indexing
If you only want to print an item when it exists, you can use a simple length check.
data = ["a", "b", "c"]
if data:
print(data[0])
else:
print("No item found")
3. Use enumerate() Instead of Manual Indexing
When you need an index while looping, enumerate() is usually cleaner and safer.
words = ["python", "coding", "lists"]
for index, word in enumerate(words):
print(index, word)
4. Use Negative Indexing Correctly
Negative indexing is useful when you want values from the end of a list Which is the point..
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
But remember that negative indexes still have limits It's one of those things that adds up..
fruits[-4] # IndexError
5. Handle User Input Carefully
User input is often stored as a string, so you may need to convert it to an integer That's the part that actually makes a difference. Which is the point..
items = ["apple", "banana", "cherry"]
user_index = int(input("Enter an index: "))
if 0 <= user_index < len(items):
print(items[user_index])
else