Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)

If you’re like me, you try things first in your code and fix the bugs as they come. One frequent bug in Python is the IndexError: list index out of range. So, what does this error message mean?

The error “list index out of range” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.

Python IndexError: List Index Out of Range

Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!

Leaving the Rat Race with Python Book

Let’s have a look at an example where this error arises:

lst = ['Alice', 'Bob', 'Carl']
print(lst[3])

The element with index 3 doesn’t exist in the list with three elements. Why is that? The following graphic shows that the maximal index in your list is 2. The call lst[2] would retrieve the third list element 'Carl'. Did you try to access the third element with index 3? It’s a common mistake: The index of the third element is 2 because the index of the first list element is 0.

  • lst[0] –> Alice
  • lst[1] –> Bob
  • lst[2] –> Carl
  • lst[3] –> ??? Error ???

Try It Yourself: Before I tell you what to do about it, try to fix the code yourself in our interactive Python shell:

Exercise: Fix the code in the interactive code shell to get rid of the error message.

How to Fix the IndexError in a For Loop? [General Strategy]

So, how can you fix the code? Python tells you in which line and on which list the error occurs.

To pin down the exact problem, check the value of the index just before the error occurs. To achieve this, you can print the index that causes the error before you use it on the list. This way, you’ll have your wrong index in the shell right before the error message.

Here’s an example of wrong code that will cause the error to appear:

# WRONG CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl']

for i in range(len(lst)+1):
    lst[i]


# Traceback (most recent call last):
#   File "C:\Users\xcent\Desktop\code.py", line 5, in <module>
#     lst[i]
# IndexError: list index out of range

The error message tells you that the error appears in line 5. So, let’s insert a print statement before that line:

lst = ['Alice', 'Bob', 'Ann', 'Carl']

for i in range(len(lst)+1):
    print(i)
    lst[i]

The result of this code snippet is still an error. But there’s more:

0
1
2
3
4
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 6, in <module>
    lst[i]
IndexError: list index out of range

You can now see all indices used to retrieve an element. The final one is the index i=4 which points to the fifth element in the list (remember: Python starts indexing at index 0!). But the list has only four elements, so you need to reduce the number of indices you’re iterating over. The correct code is, therefore:

# CORRECT CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl']

for i in range(len(lst)):
    lst[i]

Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:

  • Figure out the faulty index just before the error is thrown.
  • Eliminate the source of the faulty index.

IndexError When Modifying a List as You Iterate Over It

The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list:

l=[1,2,3,0,0,1]
for i in range(0, len(l)):
       if l[i]==0:
           l.pop(i)

This code snippet is from a StackOverflow question. The source is simply that the list.pop() method removes the element with value 0. All subsequent elements now have a smaller index. But you iterate over all indices up to len(l)-1 = 6-1 = 5 and the index 5 does not exist in the list after removing elements in a previous iteration.

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

l = [x for x in l if x]

Only non-zero elements are included in the list.

String IndexError: List Index Out of Range

The error can occur when accessing strings as well:

s = 'Python'
print(s[6])

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

s = 'Python'
print(s[5])
# n

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:

s = ('Alice', 'Bob')
print(s[2])

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

s = ('Alice', 'Bob')
print(s[1])
# Bob

Note: The index of the last element in any sequence is len(sequence)-1.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!