Question

How to diagnose and resolve "indexerror: list index out of range" errors in Python

Have you ever experienced the “indexerror: list index out of range” error in Python? It’s quite frustrating, I know. Here however we are going to dive into the topic and see how to avoid, debug and resolve such errors.


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
September 29, 2021
Accepted Answer

In order to understand what the error “indexerror: list index out of range” is we first need to know where it comes from. With a few words, this error appears when you reach the end of a list in Python. Having said that, let’s do a small deep dive on the topic to try and understand it better.

What are list indexes in Python

Before we begin, we need to know what are indexes in lists in order to resolve the error “indexerror: list index out of range”.

Let’s start with an example list in Python with 4 values in it:

SampleList = ['This', 'is', 'sample', 'list']

Python lists are 0-indexed, which means the index of the first value is 0 and the last index is n-1. In our case, we have 4 values which means the last value has an index of 3. Each value in the list has its own position starting from 0. The first value is ‘This’ and it has an index of 0, the value ‘is’ has an index of 1, and so on.

In order to access one of the values, we can use its index to do so. Let’s say we want to access the ‘sample’ value, it’s index is 2 so here is how we are going to do it:

print(SampleList[2])

When does the “indexerror: list index out of range” error appears

The error “indexerror: list index out of range” appears as soon as you reach the end of the list and try to call the next element.

Let’s take the list from the previous section.

SampleList = ['This', 'is', 'sample', 'list']

What happens if we try to access the index 4 from the list and call an element which doesn’t exist:

>>> SampleList = ['This', 'is', 'sample', 'list']                                                                       
>>> print(SampleList[4])                                                                                                
Traceback (most recent call last):                                                                                        
File "<stdin>", line 1, in <module>                                                                                   
IndexError: list index out of range                                                                                     

So, as we can see from the example, as soon as we try to call an element from the list which doesn’t exist we are presented with the “IndexError: list index out of range” error.

How to solve or avoid “indexerror: list index out of range” errors

Another scenario where the error appears is when we are iterating through lists.

Again, let’s use the already declared list.

SampleList = ['This', 'is', 'sample', 'list']

The list we have consists of strings. In such cases, it’s best to use a while loop to iterate over it.

>>> SampleList = ['This', 'is', 'sample', 'list']
>>> count = 0
>>> while count < len(SampleList):
        print(SampleList[count])
        count += 1
# Output:

This
is
sample
list

What we did is we created a count variable and compared it to the length of the list we have. As long as the count was less than the length we know there is an available index which we can use from the list.

A common error is when someone adds <= less than or equals to. In such cases, you’ll always receive the “indexerror: list index out of range” due to the while loop always entering when you have the same count and length of the list and as we know, if we have 4 values the indexes are 3 as they start from zero.

Let’s say we have a list of numbers:

ListOfNumbers =[1,2,3,4,5]

All we need to do is use the for loop:

>>> ListOfNumbers =[1,2,3,4,5]
>>> for number in ListOfNumbers:
        print number
# Output: 
1
2
3
4
5

Conclusion

When you see the error “indexerror: list index out of range” it’s always 100% related to a list and a function calling an index that doesn’t exist. Solving it would require you to find the said function and make sure it’s not trying to access a non-existent item in a list.

Remember, if you are using a loop to access items on the list, make sure the loop accounts for the fact that lists are indexed from zero rather than one.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel