When you try to get the element that does not exist in the List, an IndexError: list index out of range is raised. In this guide, we will discuss how to fix this error by providing three different solutions with examples.
Reproducing the IndexError – list index out of range
First, we will reproduce the error and then fix it. Create a List of five industries and try to access the 6th element (Index = 5) from the List.
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
print("Industries: ",data)
# Try to access element present at index-5
print(data[5])
Output
You can see that data (List) holds five elements. The index positions are 0, 1, 2, 3 and 4. The error is raised because we tried to access the element present at index – 5, which doesn’t exist.
Solution 1: Access Existing Elements by Finding the Length
Use the len() function to obtain the total number of elements present in the List. Based on the output returned by the len() function, access specific elements from the existing number of elements.
Example
Get the total number of elements from the data (List) and then access all elements one by one.
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
# Total number of items
print(len(data),"\n")
print(data[0])
print(data[1])
print(data[2])
print(data[3])
print(data[4])
Output
There are five elements in the List, so we can access elements present at index positions 0, 1, 2, 3 and 4 one after the other.
Solution 2: Specifying the Conditions
If you want to handle the error, Specify the if-else conditional statements by checking if the total number of elements (length of the list) is greater than specified index. If it is true, we can access that element. If it is false, the statement (Custom error message) inside the else block is executed.
Look at the structure:
Example
Try to access the element present at index = 5.
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
index=5
# Try to access element present at index-5
if(len(data)>index):
print(data[index])
else:
print('Index does not exists')
Output
There are only five elements present in the List (from Index 0 to 4), Index – 5 doesn’t exist. So the condition inside the if statement fails, and the statement inside the else block is executed – ‘Index does not exists.’
Solution 3: Use try-except block
If you want to handle the error, specify the try-except blocks (similar to if-else). Place the access logic under try block, and specify error handling in the except block.
Look at the structure:
Example
Try to access the element present at index = 5.
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
print("Industries: ",data)
# Try to access element present at index-5
try:
print(data[5])
except:
print('Index does not exists')
Output
There are only five elements present in the List (from Index 0 to 4); Index – 5 doesn’t exist. So, the statements under the try block raise an error, and it is handled in the except block by displaying the message – ‘Index does not exists.’
Bonus Example: Handling Error in Loop
This error also occurs when we specify an index out of range in while loop or a for loop. It will access all elements but will give an error at the end because the index element does not exist (as the index starts from 0 and goes up to the by 1).
i=0
while (i <= len(data)):
print(data[i])
i += 1
Output
In order to get rid of this error, specify the less than (<) operator instead of less than or equal to (<=) operator.
i=0
while (i < len(data)):
print(data[i])
i += 1
Output
Now, the error is not raised after accessing the last element.
Conclusion
We addressed the IndexError: list index out of range in three different ways. First, we reproduced this error with an example and then fixed it by handling it using conditional statements and try-except block. Lastly, we discussed how to handle the same error when accessing all elements within a while loop.