How to Fix IndexError - list index out of range in Python
List Index out of Range in Python occurs when we try to access an element that is beyond the range of the list. If there are n elements in a list, then we can only access elements from to index. If we try to go beyond this range we receive an error as IndexError: list index out of range.
We have various methods to solve list index out of range error and these are, using the range() function, using the in operator, using the index() function, and using the if-else statement.
What causes an IndexError in Python?
When working with lists in Python, accessing an element beyond the list's range triggers an IndexError. Python lists are zero-indexed, so a list with n elements has indexes from 0 to n-1. Negative indexes can be used to access elements from the end of the list, with -1 being the last element.
For instance, with l = [1,2,3], valid indexes are 0 to 2 (or -3 to -1 respectively). Accessing l[3] or l[-4] would cause an IndexError since those indexes are outside the range of the list.
Let's check how we can produce the list index out of range error in Python. We will create a list and then will access an index that will be out of bounds.
Output:
In the above code, there are 5 elements in the list. So we can access the elements from index = -5 to index = 4. But we are trying to access an element at index = 6. This resulted in IndexError: list index out of range.
Methods to Solve List Index out of Range in Python
There are various methods to solve list index out of range error. Let's understand them one by one.
Method 1: Using range()
Since the issue is with the index provided, we can use the range() function to generate valid indexes for accessing the elements of the list.
Syntax
range(start,stop,step)
Start
This is an optional parameter that specifies the starting point of the series. By default, it is 0.
Stop
This is a required parameter that specifies the terminating number at which the series should end.
Step
This is an optional parameter that specifies the increment of successive numbers of the series. By default, it is 1.
To learn more about range(), you can refer to Range Function in Python.
So as we read in the Introduction section if there are n elements in the list. We can access element from index = -n to index = (n-1). But here we will access elements from index = 0 to index = n-1.
We will use the range function to generate the series of indexes.
Example
Output
Method 2: Using in Operator
The in operator in Python can also be used to iterate over a list. So instead of accessing an element manually, we can use the in operator to iterate over the elements of the list.
Example
Output
Notice here the variable i is representing an element of the list. While in method 1, i was representing an index of an element of the list.
Method 3: Using index()
Python's index() function searches a list for an element and returns its non-negative index. But how can we use the index() function to iterate over the elements of the list?
If we know the last possible index then we can stop the iteration of the loop after accessing the last element. But how can we get the last element of the list? Can you guess it? We just read it in the Introduction section of the article.
You guess it right, by using the negative indexes. As the index -1 returns the element present at the last of the list. So we can use the index() function to get the last possible index and then we can use the range() function to generate a series of indexes till the last possible index.
To learn more about index(), you can refer to index() in Python.
Example
Output
Method 4: Using if-else Statement
All the methods that we saw above can be used when we try to iterate over elements of the list. But what if we want to just access a single element?
We can use the if-else statement to check whether the given index is out of bounds or not. If the given index is out of bounds, we will print "Invalid Index Provided" else we can just access the element.
Example
Output
Fix IndexError in Python loops
An IndexError in Python occurs when trying to access an index that is outside the range of a list. This is a common mistake when looping through lists using indices. A typical scenario is when the loop runs one iteration too many, attempting to access an element that doesn't exist.
Example
Attempting to run this loop will result in an IndexError because the loop tries to access colors[4], which is out of range for a list with 4 elements where the last index is 3.
Solutions
To correct this, the loop range should be set to the exact length of the list since list indices start at 0.
Corrected Code Example
Explanation
This loop now correctly iterates from 0 to 3, which are the valid indices for the colors list, thus avoiding any IndexError.
Alternative Solution
A more Pythonic solution is to iterate directly over the list items, removing the need to use indices altogether.
Explanation
By iterating directly over the elements, you eliminate the risk of an IndexError because you're not manually handling the indices.
Conclusion
- List Index out of range error in Python occurs when we try to access an element that is beyond the range of the list.
- If there are n elements in a list. Then we can only access elements from -n to (n-1) index.
- List Index out of range error can be solved using the range() function, using the in operator, using the index() function, and using the if-else statement.