You are reading solutions / Python

# IndexError: list index out of range and python

IndexError: list index out of range

## Why does this occur?

We see this error when indexing a list while using a value outside the range of indexes for the list. Today we'll take a look at some of the most common causes of this error, along with how to solve it using some practical examples.

## Cause 1: Indexing the Final List Value

This problem frequently occurs when trying to index the end of a list.

Let's say you've got a list of ten values, but you're only interested in getting the final value in the list. We could do this as shown below:

example_list = [4, 7, 1, 0, 8, 1, 4, 9, 7, 3]

last_index = len(example_list)  # 10

final_value = example_list[last_index]

print(final_value)
Out:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-68e9a1660bcf> in <module>
3 last_index = len(example_list) # 10
4
----> 5 final_value = example_list[last_index]
6
7 print(final_value)
IndexError: list index out of range

Recall that indexing in Python starts at zero. We're getting this error because we've gone outside the range of the list. Even though the list has a length of ten, its indexes only range from 0-9, making the tenth index out of range.

### Solution

We can fix the error by altering the index used to return the final list value, shown in the following solution:

example_list = [4, 7, 1, 0, 8, 1, 4, 9, 7, 3]

last_index = len(example_list) - 1  # 9

final_value = example_list[last_index]

print(final_value)
Out:
3

Now that the index is within the correct range, the code runs successfully.

An alternative way of returning list values is to use a negative index. See below for an image showing the negative indexes of example_list, followed by a solution that uses a negative index to return the final list value:

example_list = [4, 7, 1, 0, 8, 1, 4, 9, 7, 3]

final_value = example_list[-1]

print(final_value)
Out:
3

## Cause 2: Altering List while Looping

Another common cause of this error is modifying a list while looping over it. Generally, you should rarely change a data structure while looping over it.

Let's say you've got a list of colors called colors. You're not a big fan of the color blue, so you'd like to remove all blue values from the list. We can attempt this as shown below:

colors = ['blue', 'red', 'orange', 'blue', 'green']

for i in range(len(colors)):
if colors[i] == 'blue':
del colors[i]

print(colors)
Out:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-2217ef722400> in <module>
2
3 for i in range(len(colors)):
----> 4     if colors[i] == 'blue':
5         del colors[i]
6
IndexError: list index out of range

This error occurs because the del command changes the list length while in the loop.

At the start of the for loop, the length of colors is five, so the range() function generates the list [0, 1, 2, 3, 4].

Although our list length decreases every time we delete an item, the range list we are looping through will remain the same. We'll eventually run into the index error in the later stages of our for loop since range() will be providing indexes greater than the length of the list.

To avoid editing the list directly while looping over it, we utilize list comprehension.

### Solution

colors = ['blue', 'red', 'orange', 'blue', 'green']

colors = [color for color in colors if color != 'blue']

print(colors)
Out:
['red', 'orange', 'green']

In just one line of code, we can remove any blue values from colors.

List comprehension works by creating a new list (as denoted by the brackets), then utilizing a for to iterate through all values in the list. The addition of if color != 'blue' communicates to Python that we're only interested in values that aren't blue, storing these in a new list. Once the for loop has finished iterating through all of the list values, we replace the old list.

## Summary

This index error is triggered when indexing a list using a value outside of its range of indexes. The best way to avoid it is by carefully considering what range of indexes a list might have, taking into account that list indexes start at zero instead of one. As we've discussed, it's also a good idea to avoid editing a list while iterating over it, which can cause many issues.