IndexError in Python: Causes and Fixes
IndexError means your code tried to use a position that does not exist in a sequence.
This usually happens with:
- lists
- tuples
- strings
In Python, indexing starts at 0, not 1.
So if a list has 3 items, the valid indexes are:
012
If you try to access index 3, Python raises an IndexError.
Quick fix
If you are not sure whether an index exists, check it before using it:
items = ["a", "b", "c"]
index = 2
if 0 <= index < len(items):
print(items[index])
else:
print("Index is out of range")
Output:
c
Use len() to make sure the index is inside the valid range.
What IndexError means
IndexError happens when you try to access a position that is outside the valid range of a sequence.
Common examples:
- asking for an item past the end of a list
- using a negative index that goes too far left
- reading the first item from an empty list
It usually appears with:
- lists
- tuples
- strings
Python uses zero-based indexing:
letters = ["a", "b", "c"]
print(letters[0]) # first item
print(letters[1]) # second item
print(letters[2]) # third item
Output:
a
b
c
There is no letters[3] here, because the list only has 3 items.
If you need a beginner-friendly explanation of list positions, see Python lists explained.
When this error usually happens
IndexError often appears in these situations:
- Using an index that is too large
- Using a negative index that goes past the start of the sequence
- Looping with the wrong
range()values - Removing items, then trying to access an old index
- Reading user input and using it directly as an index
Here are a few common causes:
- Trying to access
items[len(items)]instead of the last valid item - Using
range(len(items) + 1)in a loop - Accessing
[0]on an empty list - Using a number from
input()without checking it - Using indexes after the sequence size changed
Example that causes IndexError
Here is a simple example:
items = ["apple", "banana", "cherry"]
print(items[3])
This list has 3 items, so the valid indexes are:
0→"apple"1→"banana"2→"cherry"
Index 3 does not exist.
Python raises this error:
Traceback (most recent call last):
File "example.py", line 3, in <module>
print(items[3])
IndexError: list index out of range
If you are dealing with this exact message, see IndexError: list index out of range fix explained.
Strings can raise the same kind of error:
word = "cat"
print(word[3])
This also fails because valid indexes are 0, 1, and 2.
How to fix IndexError
There is no single fix for every case. The right solution depends on why the bad index happened.
Check the length first with len()
If an index may or may not exist, check it first:
items = ["a", "b", "c"]
index = 1
if 0 <= index < len(items):
print(items[index])
else:
print("Invalid index")
Use valid index values only
A common mistake is using len(items) as an index.
items = ["a", "b", "c"]
print(len(items)) # 3
print(items[2]) # last valid item
If you want the last item, use:
print(items[len(items) - 1])
Or more simply:
print(items[-1])
Fix loop ranges
A loop should stop before len(sequence), not at len(sequence).
Wrong:
items = ["a", "b", "c"]
for i in range(len(items) + 1):
print(items[i])
Correct:
items = ["a", "b", "c"]
for i in range(len(items)):
print(items[i])
Output:
a
b
c
If you want a simpler way to loop, see how to loop through a list in Python.
Use enumerate() when you need both index and value
Instead of managing indexes manually, use enumerate():
items = ["a", "b", "c"]
for i, value in enumerate(items):
print(i, value)
Output:
0 a
1 b
2 c
This is often safer than writing your own index logic.
Handle empty sequences before reading the first item
This is a very common beginner mistake:
items = []
print(items[0])
Fix it by checking whether the sequence has any items:
items = []
if items:
print(items[0])
else:
print("The list is empty")
Common IndexError situations
Here are some patterns that often cause this error.
Accessing the first item of an empty list
numbers = []
print(numbers[0])
This fails because there is no first item.
Safer version:
numbers = []
if numbers:
print(numbers[0])
else:
print("No items found")
Using i + 1 inside a loop without checking the end
items = ["a", "b", "c"]
for i in range(len(items)):
print(items[i + 1])
This fails on the last loop because i + 1 becomes 3.
Safer version:
items = ["a", "b", "c"]
for i in range(len(items) - 1):
print(items[i + 1])
Mixing up item values and item indexes
Sometimes a value is treated like an index by mistake:
items = ["apple", "banana", "cherry"]
index = "banana"
print(items[index])
This is not an IndexError — it raises a TypeError because indexes must be integers.
If you want to find where an item appears, do not use the value as an index directly. See how to find an item in a list in Python.
Using list positions after pop() or remove() changed the list
items = ["a", "b", "c"]
items.pop()
print(items[2])
After pop(), the list becomes ["a", "b"], so index 2 no longer exists.
Step-by-step debugging tips
If you are not sure why IndexError is happening, check these things.
1. Print the sequence and its length
items = ["a", "b", "c"]
print(items)
print(len(items))
2. Print the index value before the failing line
index = 3
print(index)
3. Check whether the sequence is empty
items = []
print(len(items) == 0)
4. Check loop start and stop values
If you use a loop with indexes, confirm that it stops at the right point.
items = ["a", "b", "c"]
for i in range(len(items)):
print(i, items[i])
5. Read the traceback carefully
The traceback shows the exact line where the error happened. Start there.
Useful debugging commands:
print(items)
print(len(items))
print(index)
print(type(items))
for i, value in enumerate(items):
print(i, value)
These can help you answer:
- How many items are in the sequence?
- What index is the code trying to use?
- Is the sequence empty?
- Is the object really a list, tuple, or string?
IndexError vs related errors
Some Python errors look similar, but they mean different things.
IndexError
IndexError means the position does not exist in a sequence.
Example:
items = ["a", "b"]
print(items[2])
KeyError
KeyError happens when a dictionary key does not exist.
Example:
data = {"name": "Ana"}
print(data["age"])
If you want a direct comparison, see KeyError vs IndexError in Python explained.
TypeError
TypeError can happen if you use the wrong type as an index.
Example:
items = ["a", "b", "c"]
print(items["1"])
This fails because "1" is a string, not an integer.
FAQ
What causes IndexError in Python?
It happens when your code uses an index that is outside the valid range for a list, tuple, or string.
What is a valid list index?
For a list with length 3, valid indexes are 0, 1, and 2.
Can strings raise IndexError too?
Yes. Strings also use indexes, so accessing a position that does not exist raises IndexError.
How do I avoid IndexError in a loop?
Use correct range() limits, or loop directly over the items instead of hard-coding indexes.
Is IndexError the same as KeyError?
No. IndexError is for invalid positions in sequences. KeyError is for missing dictionary keys.