Categories
Blog Tech

How to resolve IndexError: list index out of range in Python [once and for all!]6 min read

There is an easy fix, and it is no joke. If you have ever encountered the IndexError message, you know the frustration of not knowing what code line is to BLAME. Especially if the code is a bit longer and contains loops… Right down the rabbit hole (…and Your lunch break is already over)…

Sounds familiar? Never miss your lunch break again due to the “code that does not listen…”. The IndexError can be just like that if you do not know where to look. Luckily enough, this post will explain the root cause so that you never see the sentence IndexError: list index out of range again.

Let’s cut right to the chase. The IndexError occurs with the LIST data type in Python (click here to learn about all Python data types).

If you see the error, you have a list in your code. Why is this useful? It’s a breakthrough since you can narrow down your interrogation (you know where to look).

Let me explain it further.

What is causing the list index out of range error?

Shall we take a simple list? (I will borrow the code from my Python 101 guide from here).

my_family = [5, "father", "mother", "brother", "sister"]
print(my_family[0]) # Prints 5
print(my_family[1]) # Prints "father"
print(my_family[2]) # Prints "mother"
print(my_family[3]) # Prints "brother"
print(my_family[4]) # Prints "sister"Code language: PHP (php)

Click here to run this code — press the green “Run” button once there

The list named my_family has multiple elements: 5, father, mother, brother, and sister (5 elements in total).

If you run the code, you will see that lines such as my_family[0] through my_family[4] are targeting individual elements of the list.

The number between the square brackets [ and ] is called the INDEX. You use it to collect any of the individual elements of a list.

Note: the index starts at 0 (zero position) — to collect the first element, you will use the index 0, and to collect the last, you will use n - 1 (where n is the number of elements in the list).

Now, if I use an index that targets an element of the list that is not there… What do you think would happen?

For instance, print(my_family[5])… Does index 5 have a corresponding element in the list? Unfortunately, no — this line will cause you Déjà vu.

So, the error happens when you target an element that is not in the list… In other words, you provided the wrong index number of something you expected that is there, but it is not…

In computer parlance, we say that the index is out of range (for a given list)… There you have it — the root cause. Let’s now see how this can complicate further…

So read on.


The IndexError on steroids: loops

Now here comes the good part. (Read more about loops here if you see this term for the first time.)

The loops can be tricky because it is not apparent that you are providing the wrong index. It is even less obvious at what point your index is not right. Let’s again borrow the code from my Python 101.

my_family = [5, "father", "mother", "brother", "sister"]

for i in (0,1,2,3,4): #The brackets contain indices
  print(my_family[i]) #Prints each of the list elementsCode language: PHP (php)

Click here to run this code — press the green “Run” button once there.

The code line that instructs Python to print each element of the list is this my_family[i]. So the variable i will be equal to 0, 1, 2, 3, and 4 as the iteration progresses.

If you try it, you will see that the code works… But it works only because the provided indices (0,1,2,3,4) have the corresponding element in the list.

What would happen if you added 5 so that the code looks like the one below? Think about it for a moment

my_family = [5, "father", "mother", "brother", "sister"]

for i in (0,1,2,3,4,5): #The brackets contain indices
  print(my_family[i]) #Prints each of the list elementsCode language: PHP (php)

Yes — the IndexError comes again.

Want to know what’s the most common Java error? Read here about it.

How to safeguard against the IndexError in a loop?

By being smart. Before you write any code that iterates over a list, make sure that you capture the list length.

The first element of any list is the index 0 (zero). That you already know. How to capture the last element? Check this code out.

my_family = [5, "father", "mother", "brother", "sister"]
list_last_el_index = len(my_family)
for i in range(0, list_last_el_index):
  print(my_family[i])Code language: PHP (php)

Click here to run this code — press the green “Run” button once there.

You capture the number of elements in the list by using len(my_family). This returns 5 (the number of elements in the my_family list).

How come we do not get the IndexError when using the list_last_el_index variable — should not the last iteration make the i variable equal to 5?

If you asked this question — congrats on the attention levels. Well, this is possible because of the range(0, list_last_el_index) line. The range function takes 0 as a starting point but it will not count through all the elements until the end.

The range function omits the last counter. In our example, this would be (0,1,2,3, and 4) — 5 (the value of list_last_el_index is OMITTED).

Do not worry if you get confused at times with the len and the range functions and still get the error. This time, it is different as you know exactly the root cause and how to fix it.

Summary

If you have ever written any Python code, it is almost certain that you have seen the IndexError: list index out of range error. This error is annoying, and sometimes it is hard to track where it comes from (especially with the larger code bases).

This post explained the root cause of this error using simple code examples: the error happens with the list data type and only when there is no corresponding element in the list at a given index.

This already gives a good clue to understanding the root cause but I did not stop there.

Loops can make your life harder when it comes to troubleshooting. Because of that, I suggest you use the len and the range function to always keep your loops within the list’s range.

You can continue learning Python in my 101 Python guide here.

P.S. Write in a comment if you see more Python errors you do not understand fully, and I will explain.


Avatar photo

By Igor Jovanovic

Founder & Full Stack Tech Consultant

Experienced tech professional with a strong track record in web services and fintech. Collaborating with Silicon Valley's multi-billion tech giants and offering a range of services committed to excellence. Check the Services page for how I can help you too.

Leave a Reply

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