If you’re like me, you try things first in your code and fix the bugs as they come. One frequent bug in Python is the
IndexError: list index out of range. So, what does this error message mean?
The error “list index out of range” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.
Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!
Let’s have a look at an example where this error arises:
lst = ['Alice', 'Bob', 'Carl'] print(lst)
The element with index 3 doesn’t exist in the list with three elements. Why is that? The following graphic shows that the maximal index in your list is 2. The call
lst would retrieve the third list element
'Carl'. Did you try to access the third element with index 3? It’s a common mistake: The index of the third element is 2 because the index of the first list element is 0.
- lst –> Alice
- lst –> Bob
- lst –> Carl
- lst –> ??? Error ???
Try It Yourself: Before I tell you what to do about it, try to fix the code yourself in our interactive Python shell:
Exercise: Fix the code in the interactive code shell to get rid of the error message.
How to Fix the IndexError in a For Loop? [General Strategy]
So, how can you fix the code? Python tells you in which line and on which list the error occurs.
To pin down the exact problem, check the value of the index just before the error occurs. To achieve this, you can print the index that causes the error before you use it on the list. This way, you’ll have your wrong index in the shell right before the error message.
Here’s an example of wrong code that will cause the error to appear:
# WRONG CODE lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): lst[i] # Traceback (most recent call last): # File "C:\Users\xcent\Desktop\code.py", line 5, in <module> # lst[i] # IndexError: list index out of range
The error message tells you that the error appears in line 5. So, let’s insert a print statement before that line:
lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): print(i) lst[i]
The result of this code snippet is still an error. But there’s more:
0 1 2 3 4 Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 6, in <module> lst[i] IndexError: list index out of range
You can now see all indices used to retrieve an element. The final one is the index
i=4 which points to the fifth element in the list (remember: Python starts indexing at index 0!). But the list has only four elements, so you need to reduce the number of indices you’re iterating over. The correct code is, therefore:
# CORRECT CODE lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)): lst[i]
Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:
- Figure out the faulty index just before the error is thrown.
- Eliminate the source of the faulty index.
IndexError When Modifying a List as You Iterate Over It
The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list:
l=[1,2,3,0,0,1] for i in range(0, len(l)): if l[i]==0: l.pop(i)
This code snippet is from a StackOverflow question. The source is simply that the
list.pop() method removes the element with value 0. All subsequent elements now have a smaller index. But you iterate over all indices up to
len(l)-1 = 6-1 = 5 and the index 5 does not exist in the list after removing elements in a previous iteration.
You can simply fix this with a short list comprehension statement that accomplishes the same thing:
l = [x for x in l if x]
Only non-zero elements are included in the list.
String IndexError: List Index Out of Range
The error can occur when accessing strings as well:
s = 'Python' print(s)
To fix the error for strings, make sure that the index falls between the range
0 ... len(s)-1 (included):
s = 'Python' print(s) # n
Tuple IndexError: List Index Out of Range
In fact, the IndexError can occur for all ordered collections where you can use indexing to retrieve certain elements. Thus, it also occurs when accessing tuple indices that do not exist:
s = ('Alice', 'Bob') print(s)
Again, start counting with index 0 to get rid of this:
s = ('Alice', 'Bob') print(s) # Bob
Note: The index of the last element in any sequence is
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.