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...

In [1]:
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
print(fruits[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-1-c97c5d1ff980> in <module>
      1 fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
----> 2 print(fruits[4])

IndexError: list index out of range

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 ???

How to Fix the IndexError in a For Loop

Here is an example of wrong code that will cause the list index error when we loop through the list.

In [3]:
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)+1):
    fruits[i]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-3-313202541958> in <module>
      1 fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
      2 for i in range(len(fruits)+1):
----> 3     fruits[i]

IndexError: list index out of range

The error message tells you that the error appears in line 3. Let us insert a print statement to print the index too.

In [4]:
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)+1):
    print(i)
    print(i, fruits[i])   
0
0 Apple
1
1 Oranges
2
2 Bananas
3
3 Mangoes
4
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-91ebb58e1df0> in <module>
      2 for i in range(len(fruits)+1):
      3     print(i)
----> 4     print(i, fruits[i])

IndexError: list index out of range

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.

In [5]:
fruits = ["Apple", "Oranges", "Bananas", "Mangoes"]
for i in range(len(fruits)):
    print(i, fruits[i])   
0 Apple
1 Oranges
2 Bananas
3 Mangoes

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.

In [6]:
prices = [100, 50, 120, 30]
for i in range(len(prices)):
    if prices[i] < 100:
        prices.pop(i)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-c8fd94b8f60d> in <module>
      1 prices = [100, 50, 120, 30]
      2 for i in range(len(prices)):
----> 3     if prices[i] < 100:
      4         prices.pop(i)

IndexError: list index out of range

You can simply fix this with a short list comprehension statement that accomplishes the same thing:

In [7]:
prices = [p for p in prices if p >= 100]
prices
Out[7]:
[100, 120]

String IndexError: List Index Out of Range

The error can occur when accessing strings in Python list.

Let us do an example.

In [8]:
greeting = "Hello!"

Strings in Python is by default a list. We can check the length of list.

In [9]:
print(len(greeting))
6

We see the length of above string list is 6. Now let us look at the below error code.

In [10]:
greeting = "Hello!"
print(greeting[6])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-f8f7fc965f5e> in <module>
      1 greeting = "Hello!"
----> 2 print(greeting[6])

IndexError: string index out of range

To fix the error for strings, make sure that the index falls between the range 0 ... len(s)-1 (included):

In [11]:
greeting = "Hello!"
print(greeting[5])
!

Tuple IndexError: List Index Out of Range

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.

In [12]:
position = (10, 20) # X,Y coordinate
print(position[2])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-12-2a4190525b4a> in <module>
      1 position = (10, 20) # X,Y coordinate
----> 2 print(position[2])

IndexError: tuple index out of range

To fix the error, we have to use the correct index.

In [13]:
position = (10, 20) # X,Y coordinate
print(position[1])
20

Again, start counting with index 0 to get rid of this:

Another example of correct indexing in Python tuple.

In [14]:
position = (10, 20) # X,Y coordinate
print(position[1]) # Y coordinate
20

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.