Python IndexError: List Index Out of Range
In this notebook, I will go in deeper about the most common error while accessing the index in Python.
IndexError: list index out of range
Let's have a look at list of examples where this error arises...
Let us look at the following list...
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
print(fruits[4])
Note: In Python indexing starts from 0, therefore for the above list indexing starts from 0 and ends at 3.
The element with index 4 doesn’t exist in the list with three elements. Why is that? The following graphic shows that the maximal index in your list is 3. The call lst[3] would retrieve the 4th list element 'Mangoes'. Did you try to access the 4th element with index 4? It’s a common mistake: The index of the 4th element is 3 because the index of the first list element is 0.
- fruit[0] -> Apple
- fruit[1] -> Oranges
- fruit[2] -> Bananas
- fruit[3] -> Mangoes
- fruit[4] -> ??? Error ???
Here is an example of wrong code that will cause the list index error when we loop through the list.
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)+1):
fruits[i]
The error message tells you that the error appears in line 3. Let us insert a print statement to print the index too.
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)+1):
print(i)
print(i, fruits[i])
As we see above, the code is erroring out at index 4 because there is no element at index in the above list.
Let us fix the above code and rerun it.
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)):
print(i, fruits[i])
The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list with list.pop() command.
prices = [100, 50, 120, 30]
for i in range(len(prices)):
if prices[i] < 100:
prices.pop(i)
You can simply fix this with a short list comprehension statement that accomplishes the same thing:
prices = [p for p in prices if p >= 100]
prices
The error can occur when accessing strings in Python list.
Let us do an example.
greeting = "Hello!"
Strings in Python is by default a list. We can check the length of list.
print(len(greeting))
We see the length of above string list is 6. Now let us look at the below error code.
greeting = "Hello!"
print(greeting[6])
To fix the error for strings, make sure that the index falls between the range 0 ... len(s)-1 (included):
greeting = "Hello!"
print(greeting[5])
In fact, the IndexError can occur for all ordered collections where you can use indexing to retrieve certain elements. Thus, it also occurs when accessing tuple indices that do not exist:
Let us create a tuple first of two elements and access the 2nd element in the tuple as shown below.
position = (10, 20) # X,Y coordinate
print(position[2])
To fix the error, we have to use the correct index.
position = (10, 20) # X,Y coordinate
print(position[1])
Again, start counting with index 0 to get rid of this:
Another example of correct indexing in Python tuple.
position = (10, 20) # X,Y coordinate
print(position[1]) # Y coordinate
Conclusion: Keep in mind that Python indexing starts from 0. Then it is every easy to avoid the Python indexing error for all the data structures.
Related Notebooks
- R List Tutorial
- How To Convert Python List To Pandas DataFrame
- A Study of the TextRank Algorithm in Python
- How To Get Measures Of Spread With Python
- Calculate Implied Volatility of Stock Option Using Python
- How to Convert Python Pandas DataFrame into a List
- Remove An Item From A List In Python Using Clear Pop Remove And Del
- Pandas Groupby Count of Rows In Each Group
- How to Generate Embeddings from a Server and Index Them Using FAISS with API