Solution for IndexError: list index out of range in python

If you are new to python and wondering what is “IndexError: list index out of range“, here is the answer. This is a stupid bug in your program that happens when your application tries to access an index that does not exist.

Sometimes it’s very frustrating to figure out where this bug is happening in your program.

An IndexError exception is thrown when the program is trying to access a nonexistent index in a List, Tuple, or String

Python lists are 0-indexed. It means the list in python starts with index 0. If you have 3 elements in python, the last element’s index will be 2 and not 3. If your program tries to access index 3, the compiler will show IndexError: list index out of range .indexerror: list index out of range

Take a look at the example below

indexerror: list index out of range

From the above example, it is clear that the first element in the list will have index 0 and the last element in the list will have an index len(_list) - 1. In the above example, we had a list of where this error happened. The same error could also occur with tuple with error: indexerror: tuple index out of range.

if you try to access the non-existing index in a Tuple or String, the compiler will throw the same exception. The wordings would be slightly different in the case of the tuple, the error would be IndexError: tuple index out of range

A common pattern where “indexError: list index out of range” error occurs.

  • Checking for the element in the list incorrectly. If you have 3 elements in the list and you are checking to see if the list contains the 4th element, the compiler will throw this error.
_list = ["red", "blue", "black"]
if _list[3]:
   print("We have color at index 3")
else:
  print("There is no color at index 3")
''' Output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
'''

In the above example, we are trying to check if there is any value at index 3 using the if statement. Before producing the result for the if statement, the compiler will execute _list[3] and throw the “index out of range” error.

How to fix “indexError: list index out of range”.

The solution to the above problem would be, before accessing the index, to check the length of the list to make sure the index is not out of range.

colors = ["red", "blue", "black"]
if len(colors) > 3 and colors[3]:
   print("We have color at index 3")
else:
  print("There is no color at index 3")
''' Output
There is no color at index 3
'''

The other solution could be using enumerate function to iterate through the list.

colors = ["red", "blue", "black"]
for i, color in enumerate(colors):
  print("The index of color %s is %s" %(color, i)) 
''' Output
The index of color red is 0
The index of color blue is 1
The index of color black is 2
'''

indexError: list index out of range for loop

Another example, where the program tries to access nonexisting index while iterating through for loop

scores = [20,40,60,80]
for j in scores:
     print(j)
     for i in range(0, scores[j]):
         print(i)
'''Output
20
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range
'''

basically, the above program fails due to the value j in scores being much higher than the length of list scores. So j is not 0, 1, 2, 3, but rather 20, 40, 60, 80.

When the program executes for i in range((0, N[j]), it looks for the element in scores at index 20, which doesn’t exist, and throws IndexError.

This error is avoidable by selecting the name of the variable wisely. for example:

''' First option'''
scores = [20,40,60,80]
for score in scores:
       print(score)
       for i in range(0, score):
           print(i)
''' if you still want to stick with the variable name, you can try second option'''
scores = [20,40,60,80]
for j in range(len(scores)):
        print(j)
        for i in range(0, scores[j]):
            print(i)

list index out of range python split

This usually happens when a program tries to access an element from an array generated from the split function. For example, a variable is initialized and assigned a value of the output of the split function, and the split function produces no result.

The program tries to access the first element of the array.

some_string = 'Split this string on , and put them in array'
array = some_string.split(',')
last_element = array[2]
''' Output
Error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
'''

Fixing indexerror: tuple index out of range

Tuple throws the same error when the application tries to access the unavailable index. for example

>>> countries = ('US', 'UAE', 'INDIA', 'CANADA')
>>> countries[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

In the above example, the code is trying to access the fifth element in the tuple which is not available. To fix this kind of problem, you can use the element instead of the index or start with the 0th element.

Solution to Fix the indexerror: tuple index out of range

>>> for country in countries:
...  print("Current country is:" + country)
... 
Current country is:US
Current country is:UAE
Current country is:INDIA
Current country is:CANADA

Written by

I am a software engineer with over 10 years of experience in blogging and web development. I have expertise in both front-end and back-end development, as well as database design, web security, and SEO.

Leave a Reply

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