Python

Indexerror: list index out of range : Lets Fix it

Indexerror list index out of range occurs when we access any index which is more than the length of the list. For example, if the list has five elements and we try to access the index in sixth place. This is the root cause of this error.

 

Indexerror list index out of range (Cause with Example)-

Let’s take an example where we declare the list with some dummy element. Now we will try to access any element which is

data=[1,2,3,4]
print(data[5]) 

Indexerror list index out of range (Prevention)-

We can easily fix this error with this golden rule. We need to check the index number before putting it into the subscript. It should be less than the length of the list. Here we will check the length. if the index is more than the length of the list, We will only call the index till length only.

data=[1,2,3,4]
length = len(data)
index=5
#preventing the 
if (index>length):
  index=length
else:
  pass
print(index)
print(data[index])

Indexerror list index out of range (Handling)-

In the above section, We have seen how to prevent this error. But in the run time we get so many scenarios where this prevention is not enough. So in this section, we will see how to handle this error using exceptional handling. Please refer to the below code.

data=[1,2,3,4]
index=5
try:
  print(data[index])
except IndexError:
  print(" It is an IndexException")
list index out of range cause

Most Importantly Even if we do not explicitly define the exception name. We can use the only except keyword. Also, we can use the Exception keyword in the place of IndexError because it is the Base class Exception.

Conclusion –

Well, the list index out of range is one of the common errors for python programmer. I hope all the above section, Clears you the root cause and fix the above error. Still, If you have any doubt about this issue, please comment below in the comment box. We are always ready to help you.

Thanks 

Data Science Learner Team