Python IndexError: List Index Out of Range (How to Fix the Bug)

Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)
Python / By Chris

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.

Python IndexError: List Index 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)!

Leaving the Rat Race with Python Book
Let’s have a look at an example where this error arises:

lst = [‘Alice’, ‘Bob’, ‘Carl’]
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[2] 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[0] –> Alice
lst[1] –> Bob
lst[2] –> Carl
lst[3] –> ??? 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:


lst = [‘Alice’, ‘Bob’, ‘Ann’, ‘Carl’]
for i in range(len(lst)+1):

Traceback (most recent call last):

File “C:\Users\xcent\Desktop\”, line 5, in


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):
The result of this code snippet is still an error. But there’s more:

Traceback (most recent call last):
File “C:\Users\xcent\Desktop\”, line 6, in
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:


lst = [‘Alice’, ‘Bob’, ‘Ann’, ‘Carl’]
for i in range(len(lst)):
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:

for i in range(0, len(l)):
if l[i]==0:
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’

To fix the error for strings, make sure that the index falls between the range 0 … len(s)-1 (included):

s = ‘Python’


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’)

Again, start counting with index 0 to get rid of this:

s = (‘Alice’, ‘Bob’)


Note: The index of the last element in any sequence is len(sequence)-1.

Where to Go From Here?
Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join the free webinar now!

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 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.

Do you want to work from home and earn a healthy living as a freelance developer? There never has been a better time! Freelance Developers make $51 per hour, on average, in the US.

Complete Guide to Freelance Developing & Programming (IT)

What is Freelancing Anyways?

Definition: Freelancing is the act of delivering a service to another business or another customer in exchange for a defined rate.

If you travel back in time—say, ten years—freelancing would be the act of delivering your services to another business: a B2B (business-to-business) transaction.

But, since the appearance of freelancing platforms such as Upwork or Fiverr, it more and more became a B2C (business-to-customer) transaction. There are plenty of people, often employees, who need your services to become more and more productive.

In essence, you’re solving problems for other people. These people can be businesses, private persons, or employees. These people hire you to solve a problem for them. This makes perfect sense: in our world, everyone is a business owner.

As a person, employee, or freelancer, you are a one-person business that gets hired by organizations and other businesses.

As an employee, you are already a freelancer—have a look at the definition again. You sell your services to another party. You get paid by the hour. If you have experience as an employee, you have experience as a freelancer, too, because being an employee is nothing but a special case of being a freelancer.

But there are many more forms of freelancing. As an employee, you’re in a contract between your employer and yourself that ranges for many months. As a freelancer, you can also have these types of contracts: You can agree to contracts that range many years—in fact, businesses hire freelancers often on a long-term basis. If it makes economic sense to hire you once, why shouldn’t it make sense to hire you on a regular basis? But you can also have much smaller contracts that range only for a few hours.

Freelancing comes with all kinds of advantages and disadvantages. But as the term freelancing is so broadly defined, you cannot really generalize those: no advantage and no disadvantage will apply to any type of freelancing gig. Well, as a freelancer, you can aim for the best of both worlds: income security and higher income—if you design your freelancing business in an intelligent way.

Let’s have a deeper look into the freelance developer niche—is it attractive?

Normality of the organization of the world’s talents undergoes a massive transformation.

Normality before 2020: You work at a company location as an employed worker.
Normality after 2021: You work remotely as an independent freelancer on a per-project basis.
Here’s how the Google search trends looks like for remote work:

… and for freelancing:

Some of the most successful companies today are in the area of remote work and freelancing: Upwork, Fiverr, Zoom, and Atlassian—just to name a few.

So, how are the numbers—is freelancing really growing in the US? The answer is: YES!

Freelance Developer Skills

What skills do you need to succeed as a freelance developer?

Teaching many freelancing students, I have come to learn that most don’t believe they have all the skills they need to get started as a freelance developer. And why should they come to that conclusion given that there are so many different skills to be learned?

Business Strategy
Copy Writing
Yet, while all of the listed skills are highly important for your freelancing business, I have yet to meet a single person that is highly skilled in all of those.

Consider each of those skills to be an axis of a multi-dimensional coordinate system. Now, you can assign to each person a score between 0% and 100% for each skill. Here’s the skill score card for two imaginary freelancers Alice and Bob:

Freelancer Skills

Given are two freelancers: Alice and Bob.

Alice has a talent for marketing and copywriting. She’s an average coder and not very good in administration.
Bob is a master coder—the classical nerd—but he’s not skilled in marketing, sales, communication. He is a great administrator though.
Here’s the million dollar question: who’s the better freelance developer?

Posed like this, you may find the question ridiculous. Of course, it depends how both position themselves in the marketplace. Alice may have a small edge over Bob due to her people, sales, and marketing skills. However, it will be a close win because Bob’s programming skills are also highly valued by the marketplace.

Both will earn some money between minimum and maximum wage (say, around the average earnings of $51 per hour for freelance developers). The key is to understand that every single person on the planet has some value to the marketplace.

Let’s have a look at a third freelancer: YOU.

Freelancer Skills to Hourly Rate

Say, Alice earns $55 per hour due to her ability to sell her skills. Bob earns $51 per hour due to his super programming skills.

Suppose you are a beginner in both: sales and programming. Your programming skills are only 30% and your sales skills are even worse with 10%. But you have solid networking, communication, and empathy skills as a human being. That’s all you need—you can offer value to the marketplace! Your skills are worth $23 per hour!

The only thing left for you to do is to sell your skills, keep engaging with the marketplace, and increase your skills over time. You’ll increase your sales and marketing skills. You’ll build confidence. You’ll increase your programming skills over time. By engaging the marketplace, you automatically increase your value to it. Your hourly rate increases with it!

If you want to build your new freelancing business online, check out the world’s #1 Python Freelancer Course that gives you a step-by-step framework perfected by thousands of freelancing students like you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Psst. Yeah, you. Want some marketing secrets "gurus" never share?

Get them every month from your favorite teen entrepreneur - for free. After all, sharing is caring. ❤️🚀

🔒 No spam. I promise. 🔒