Python IndexError: List Index Out of Range [Easy Fix]

4.4/5 - (8 votes)

Key Points:

  • To solve the “IndexError: list index out of range”, avoid do not access a non-existing list index. For example, my_list[5] causes an error for a list with three elements.
  • If you access list elements in a loop, keep in mind that Python uses zero-based indexing: For a list with n elements, the first element has index 0 and the last index n-1.
  • A common cause of the error is trying to access indices 1, 2, ..., n instead of using the correct indices 0,1, ..., (n-1).

Python IndexError: List Index Out of Range [Easy Fix]

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.

Minimal Example

Here’s a screenshot of this happening on my Windows machine:

Python IndexError: List Index Out of Range

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

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

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

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

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.

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:

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

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

# Traceback (most recent call last):
#   File "C:\Users\xcent\Desktop\", 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):

The result of this code snippet is still an error.

But there’s more:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\", line 6, in <module>
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 zero-based indexing: 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:

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

for i in range(len(lst)):

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:

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 fix this with a simple 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.

Check out this example:

s = 'Python'

Genius! Here’s what it looks like on my machine:

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

s = 'Python'
# 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')

No. You didn’t? ๐Ÿ˜…

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

s = ('Alice', 'Bob')
# Bob

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

Programmer Humor

“Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want.”xkcd

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!