In this article, let us see what IndexError is, what causes IndexError, and how to fix it!
If you have an error message that looks something like this and you’re looking to fix it:
Traceback (most recent call last):
File "/home/main.py", line 3, in <module>
print(list1[10])
IndexError: list index out of range
Then you have come to the right place. The above is an IndexError and that is all we’ll be dealing with today.
Let us start by understanding IndexError and its root causes.
IndexError & Its Root Causes
What is Index
In the programming world, an index is a number used to refer to the position of an element in a given sequence. This sequence could be anything like lists, sets, tuples, and so on.
For example, here’s a simple list with 4 items:
Python uses zero-based indexing. This means that indexes start from 0 instead of 1. In other words, the index of the first item will be 0, the index of the second item will be 1, and so on:
In other words, this sequence has 4 items and we use the indexes 0, 1, 2, and 3 to refer to each one of them. It is worth noting that we can also use negative indices to refer to the elements in a sequence in Python.
This is useful in programming when we want to single out an element and operate with it. For example, the following program prints the 3rd element in the list:
Now that we have learned what is an index exactly, let’s see what can go wrong when working with indexes, i.e. the IndexError.
What is IndexError?
IndexError is an error raised by Python when you try to access an element in a sequence with an index that is out of bounds.
Here is the exact definition from the official Python documentation:
Raised when a sequence subscript is out of range.
As long as you refer to the elements using the correct indexes, i.e. those that are within bounds, there won’t be any IndexErrors.
In other words, you must only refer to the elements ‘apple’, ‘ball’, ‘cat’, or ‘dog’.:
my_list = ["apple", "ball", "cat", "dog"]
#printing the last element
print(my_list[-1])
#editing a the first element
my_list[0] = "air"
#creating a sublist using slicing
animals = my_list[2:4]
But if you try to refer to an element using an index that is out of bounds, you’ll trigger the IndexError:
Common causes of IndexError
I’ve compiled a few reasons below as to why you might have encountered the IndexError:
Cause#1: Forgetting indexing starts from 0
The typical cause for triggering IndexError is people naturally forget that the index for a sequence starts from 0, not 1.
So double-check your program and ensure your index falls within the valid range.
To find the valid range of a sequence, remember that it’s from 0 to n-1 for a sequence containing n elements.
For instance, if a sequence’s length is 70 elements, then the range is 0-69.
Python also allows negative indexes. The range for negative indexes ranges from -n to -1. The IndexError will be raised here as well if you use an invalid negative index.
Cause#2: Trying to refer to an element with an out-of-bound index
As explained earlier, if you try to refer to an element of a sequence with an out-of-bound index, the Python interpreter will raise an IndexError.
This is because a valid index points to some element in the list. Whereas an index that is out of bounds points to nothing. Thereby prompting the interpreter to trigger the IndexError:
Cause#3: Using indices with an empty list
If you try to access an element inside an empty list this will result in an error as there is no element to access from in the first place.
my_empty_list = []
print(my_empty_list[3]) #ANY other index would also lead to an error for that matter
Traceback (most recent call last):
File "/home/main.py", line 4, in <module>
print(my_empty_list[3])
IndexError: list index out of range
Cause#4: Passing the wrong number when working with range()
Another common mistake that leads to an IndexError is when we pass the wrong argument or integer to the range() function and it ends up calling the sequence with the wrong index.
Look at this piece of code with the range() that causes the error:
my_list = ["apple", "ball", "cat", "dog"]
for i in range(5):
print(my_list[i])
Can you spot what is wrong with the above for loop statement?
The problem here is that we have passed the number 5 to the range() function. As you might know, the range() function returns a list from 0 to n-1, where n is the number passed in. Hence here, we are saying it to print the values in positions from 0 to 4 But we don’t have a position 4 in my_list!
That is why in our output, the range() function will appropriately execute from the indexes 0 to 4 then it will trigger an error when it tries to execute my_list[4].
Apple
Ball
Cat
Dog
Traceback (most recent call last):
File "/home/main.py", line 4, in <module>
print(my_list[i])
IndexError: list index out of range
Here’s a visualization of the same:
How to avoid IndexError
Errors are inevitable in Python. That being said, we can still take precautions to minimize to the best of our abilities.
So in this section, we’ll learn a few techniques that you can implement in your program to avoid IndexError.
Firstly remember that the only way to avoid an IndexError in Python is to ensure that we do not try to access an element from an index that is out of range.
We can avoid it by using the following methods:
Tip#1: Checking and knowing the length of the sequence beforehand
It’s good practice to know the length or size of the sequence you’re working with before you perform any operations using indexes.
Hence next time, keep in mind the exact size of your sequence!
How to find the length of a sequence
Sometimes if the sequence is not small and it is cumbersome to count the number of items, you can always use the len() function to get the length of a sequence;
For example, here’s a list:
>>> my_num_list = [0, 1, 2, 3, 4, 5, 6]
>>> print(len(my_num_list))
7
You can take this a step further by including the len() function as input to the range() function:
my_list = ["apple", "ball", "cat", "dog"]
for i in range(len(my_list)):
print(my_list[i])
apple
ball
cat
dog
In this way, you can make sure that your loops don’t try to access elements that are out of range!
Tip#2: Using try-except block
Using try-except is a one-size-fits-all solution when it comes to handling any and all types of error.
Here’s try-except in action:
my_list = ["apple", "ball", "cat", "dog"]
try:
print(my_list[10])
except IndexError:
print("Error: IndexError was raised. Please enter a valid list index!")
Error: IndexError was raised. Please enter a valid list index!
I hope you have already read our article on the top 7 exceptions in Python, as those are the ones that occur 80% of the time in our day-to-day life as a Python programmer, if not, I suggest heading over to the article linked below!
7 Most Common In-Built Exceptions in Python!
And with that tip, I will end this article.
Congratulations on making it to the end of the article, not many have the perseverance to do so!
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Related Articles
ValueError: A Step By Step Troubleshooting Guide!
NameError: A Step By Step Troubleshooting Guide!
AttributeError: A Step By Step Troubleshooting Guide!
TypeError: A Step By Step Troubleshooting Guide!
Thanks to Namazi Jamal for his contributions in writing this article!