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 the index which 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 .

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 index len(_list) – 1. In the above example, we had a list where this error happened. The same error could also occur with tuple and string.

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 if statement. Before producing the result for 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, 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 is 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.

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 output of split function, and split function produces no result. 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
'''

2 thoughts on “Solution for indexerror: list index out of range in python”

  1. n=int(input())
    grid=[]
    
    sum=0
    s=0
    k=4
    for i in range(n):
        lists=[int(i) for i in input().split()]
        grid.append(lists)
        
    for j in range(len(grid)):
        sum=sum+grid[j][j]
        k=k-1
        s=s+grid[j][k]      
    print(sum)    
    print(s) 

    when I run my program it shows
    IndexError:List index out of range
    and it shows the error is in line
    s=s+grid[j][k]
    Please help me to solve this problem and tell me where i am going wrong

  2. What input you are providing to this program?
    I see you are assigning k=4, your grid is always [n x 1 ] matrix. in line this s=s+grid[j][k] when K = 3 will always show error ( it might pass first loop for k = 0.

    What are you trying to do in this code?

Comments are closed.

Scroll to Top