IndexError: list index out of range and python
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:
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.
We can fix the error by altering the index used to return the final list value, shown in the following solution:
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:
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:
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.
In just one line of code, we can remove any blue values from
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.
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.