How to Fix the “List index out of range” Error in Python (2023)

At many points in your Python programming career, you’re going to run into the “List index out of range” error while writing your programs. What does this mean, and how do we fix this error? We’ll answer that question in this article.

The short answer is: this error occurs when you’re trying to access an item outside of your list’s range. The long answer, on the other hand, is much more interesting. To get there, we’ll learn a lot about how lists work, how to index things the bad way and the good way, and finally how to solve the above-mentioned error.

This article is aimed at Python beginners who have little experience in programming. Understanding this error early will save you plenty of time down the road. If you’re looking for some learning material, our Python Basics track includes 3 interactive courses bundled together to get you on your feet.

Indexing Python Lists

Lists are one of the most useful data structures in Python. And they come with a whole bunch of useful methods. Other Python data structures include tuples, arrays, dictionaries, and sets, but we won’t go into their details here. For hands-on experience with these structures, we have a Python Data Structures in Practice course which is suitable for beginners.

A list can be created as follows:

>>> x = [1, 'a', 2.3, [0, 1], 1, 4]

Instead of using square brackets ([]) to define your list, you can also use the list() built-in function.

There are already a few interesting things to note about the above example. First, you can store any data type in a list, such as an integer, string, floating-point number, or even another list. Second, the elements don’t have to be unique: the integer 1 appears twice in the above example.

The elements in a list are indexed starting from 0. Therefore, to access the first element, do the following:

>>> print(x[0])

Our list contains 6 elements, which you can get using the len() built-in function. To access the last element of the list, you might naively try to do the following:

>>> print(x[6])IndexError: list index out of range

This is equivalent to print(x[len(x)]). Since list indexing starts from 0, the last element has index len(x)–1. When we try to access the index len(x), we are outside the range of the list and get the error. A more robust way to get the final element of the list looks like this:

>>> print(x[len(x)-1])

While this works, it’s not the most pythonic way. A better method exploits a nice feature of lists – namely, that they can be indexed from the end of the list by using a negative number as the index. The final element can be printed as follows:

>>> print(x[-1])4

The second last element can be accessed with the index -2, and so on. This means using the index -6 will get back to the first element. Taking it one step further:

>>> print(x[-7])IndexError: list index out of range

Notice this asymmetry. The first error was trying to access the element after the last with the index 6, and the second error was trying to access the element before the first with the index -7. This is due to forward indexing starting at 0 (the start of the list), and backwards indexing starting at -1 (the end of the list). This is shown graphically below:

How to Fix the “List index out of range” Error in Python (1)

Looping Through Lists

Whenever you’re working with lists, you’ll need to know about loops. A loop allows you to iterate through all the elements in a list.

The first type of loop we’ll take a look at is the while loop. You have to be a little more careful with while loops, because a small mistake will make them run forever, requiring you to force the program to quit. Once again, let’s try to naively loop through our list:

>>> i=0>>> while i <= len(x):... print(x[i])... i+=11a2.3[0, 1]14IndexError: list index out of range

In this example we define our index, i, to start from zero. After every iteration of our while loop, we print the list element and then go to the next index with the += assignment operator. (This is a neat little trick, which is like doing i=i+1.)

By the way, if you forget the final line, you’ll get an infinite loop.

We encountered the index error for the same reason as in the first section – the final element has index len(x)-1. Just modify the condition of the while statement to reflect this, and it will work without problems.

Most of your looping will be done with a for loop, which we’ll now turn our attention to. A better method to loop through the elements in our list without the risk of running into the index error is to take advantage of the range() built-in function. This takes three arguments, of which only the stop argument is required. Try the following:

>>> for i in range(len(x)):... print(x[i])1a2.3[0, 1]14

The combination of the range() and len() built-in functions takes care of worrying about when to stop indexing our list to avoid the index out of range error entirely. This method, however, is only useful if you care about knowing what the index is.

For example, maybe you want to print out the index and the element. In that case, all you need to do is modify the print() statement to print(i, x[i]). Try doing this for yourself to see the result. Alternatively, you can use The enumerate() function in Python.

If you just want to get the element, there’s a simpler way that’s much more intuitive and readable. Just loop through the elements of the list directly:

>>> for element in x:... print(element)1a2.3[0, 1]14
def get_value(index): x = [1, 'a', 2.3, [0, 1], 1, 4] return x[index]

If the user inputs an index outside the range of the list (e.g. 6), they’ll run into the list index error again. We can modify the function to check the input value with an if statement:

def get_value(index): x = [1, 'a', 2.3, [0, 1], 1, 4] if -len(x) <= index and index <= len(x)-1: result = x[index] else: result = 'Index out of range. Try again.' return result

Doing this prevents our program from crashing if the index is out of range. You can even use a negative index in the above function.

There are other ways to do error handling in Python that will help you avoid errors like “list index out of range”. For example, you could implement a try-exceptaa block instead of the if-else statement.

To see a try-except block in action, let’s handle a potential index error in the get_value() function we wrote above. Preventing the error looks like this:

def get_value(index): x = [1, 'a', 2.3, [0, 1], 1, 4] try: result = x[index] except IndexError: result = 'Index out of range. Try again.' return result

As you can probably see, the second method is a little more concise and readable. It’s also less error-prone than explicitly checking the input index with an if-else statement.

Master the “List index out of range” Error in Python

You should now know what the index out of range error in Python means, why it pops up, and how to prevent it in your Python programs.

A useful way to debug this error and understand how your programs are running is simply to print the index and compare it to the length of your list.

This error could also occur when iterating over other data structures, such as arrays, tuples, or even when iterating through a string. Using strings is a little different from using lists; if you want to learn the tools to master this topic, consider taking our Working with Strings in Python course. The skills you learnt here should be applicable to many common use cases.

Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated: 12/10/2023

Views: 6325

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.