Lists are one of the most used data structures in Python. You might have gotten the message “IndexError: list index out of range” when your program ran into an error while using lists. In this article, we will discuss how to avoid this error by studying the IndexError in Python.
What is an IndexError in Python?
IndexError is an exception in python that occurs when we try to access an element from a list or tuple from an index that is not present in the list. For example, we have a list of 10 elements, the index is from 0 to 9. If we try to access an element at index 10 or 11 or more, it will cause the program to raise IndexError with the message “IndexError: list index out of range” as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The list is:", myList)
index = 10
element = myList[index]
print("Element at index {} is {}".format(index,element))
Output:
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
element = myList[index]
IndexError: list index out of range
Similarly, if we have a tuple consisting of 10 elements, the index of the elements is in the range 0 to 9. If we try to access an element at index 10 or more, the program will cause IndexError as follows.
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
element = myTuple[index]
print("Element at index {} is {}".format(index,element))
Output:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
element = myTuple[index]
IndexError: tuple index out of range
Here, we have tried to access an element at index 10 from a tuple having only 10 elements. Hence, the program runs into an IndexError exception.
How to Avoid IndexError in Python?
We can either handle the index error exception or preempt it. To preempt, we can use if-else blocks. To handle the exception once it has occurred, we can use exception handling in Python.
Preempt IndexError Using If-Else Blocks
The only way to avoid an IndexError in python is to ensure that we do not access an element from an index that is out of range. For example, if a list or a tuple has 10 elements, the elements will only be present at indices 0 to 9. So, we should never access the element at index 10 or more. To do this, we can use if-else statements to check if the index is in the correct range or not as follows.
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
if index <= 9:
element = myTuple[index]
print("Element at index {} is {}".format(index, element))
else:
print("Index should be smaller.")
Output:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.
Handle IndexError Using Try-Except Blocks
Alternatively, we can use python try except blocks to handle the IndexError exception after the program raises it. Using this way, we cannot avoid the IndexError exception but we can make sure that the program doesn’t terminate prematurely after IndexError is raised.
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
try:
element = myTuple[index]
print("Element at index {} is {}".format(index, element))
except IndexError:
print("Index should be smaller.")
Output:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.
Conclusion
In this article, we have discussed IndexError in python. We have also discussed ways to above this exception. You can read more about python lists in this article on list comprehension.
To learn more about python programming, you can read this article on string manipulation. You might also like this article on python simplehttpserver.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.