IndexError: List Index Out of Range

In python, whenever we work with lists and want to access the list items from an index, whenever we access out of bound or non-existing items, the compiler throws an exception. Then, facing and the …

IndexError List Index Out of Range

In python, whenever we work with lists and want to access the list items from an index, whenever we access out of bound or non-existing items, the compiler throws an exception.

Then, facing and the index error is common, and solving such error is also not an issue. We can simply solve this by simple debugging.

“IndexError: list index out of range” this error statement is divided into two parts

  1. IndexError: Index error shows that error occurs due to some issue in the index.
  2. List index out of range means the index you want to access does not exist.

Let’s take the example of while loop to understand it better.

Example:

#indexError in python
#initializing variables
mobile = ["Android", "Apple", "Windows"]
count = 0 
#using while loop
while count <= len(mobile):
	print(mobile[count])
	count += 1

In this example, 

First, we have initialized the two variables, mobile, and count.

Then, we used the while loop, inside the while loop, used the condition “<=” length of the list.

Then, used print function to print the list and count+=1.

Output:

Android
Apple
Windows
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-b20057797134> in <module>
      3 
      4 while count <= len(mobile):
----> 5         print(mobile[count])
      6         count += 1

IndexError: list index out of range

In the above example, we have encountered the IndexError, because we are accessing the elements less than equal to (<=) the length of the list “mobile.”
To solve this error, we will just make the slightest change. We will just remove “=” from <= and simply write “<.”

Solved Example:

#Solving IndexError
#list out of rang in PyCharm
#Initializing variables
mobile = ["Android", "Apple", "Windows"]
count = 0 
#Using while loop
while count <len(mobile):
	print(mobile[count])
	count += 1

Output:

Android
Apple
Windows

In an above-solved example, we solved the IndexError by just changing <= to <, and that’s all. 

Table of Contents

Conclusion:

In this article, we discussed the “IndexError: list index out of range.”

Index error occurs when we try to access the non-existing index, and how can you solve it with simple debugging.

Suggested Read: 500 Internal server error

Leave a Comment