Python Index Error: Index Out of Range

Nov 23, 2021 12:29:54 PM | Python Index Error: Index Out of Range

Do you have an Index Out of Range error in your Python code? In this Airbrake how-to, we go over what it is and how to fix it.

Introduction

Today, we’re making our way through our in-depth Python Exception Handling series. In this article, we’ll discuss the Python IndexError: Index Out of Range. If you read The 2022 Airbrake Error Data Report, you'll see that 28% of Python projects contain IndexErrors. That's why it's important to know how to resolve this error.

Throughout this post, we’ll examine the Index Out of Range error in detail, starting with where it sits in the larger Python Exception Class Hierarchy, why it occurs, and how to fix it. 

Hierarchy

Like most Python errors, the IndexError derives from the LookupError class, which is inherited from the built-in BaseException. 

Within the LookupError class, there are two Errors listed:

  • BaseException 
    • LookupError
      • IndexError 
      • KeyError

Now that you have an idea where the error is within the Python hierarchy, let’s continue on to what it is. 

What is the Index Out of Range Error? 

Python supports the indexing of list elements. This helps access iterable items and perform operations on them, such as printing or looping through elements. But, if you mention an index in your code that is outside the range of the list, Python will throw an IndexError telling you that the list index is out of range.

Here’s an example: When we try to access an element using an index that is outside the range of that list, you’ll receive a “List index out of range” error. In this case, the print(a[5]) refers to a list that doesn’t exist. 

Something to keep in mind: A reference lists elements by their numeric position beginning with zero. Using the same example above, you would reference the first element with an index of 0 (e.g. a[0]) and to index the last element, you would use a[3]. 

How to Handle an IndexError Exception

The only way to avoid this error is to mention the indexes of list (iterable) elements properly.

A try-except block can also be used to find and handle an IndexError. If an exception occurs during execution, the exception will be caught up in the except block.

Example

Output

Want to learn more about IndexErrors? Check out our blog post, Python Exception Handling: IndexError where we go into depth about this error.

Why Use Airbrake 

Code riddled with IndexErrors? Uncover and resolve errors such as an Index Out of Range, quickly. Airbrake Error & Performance Monitoring will tell you exactly where the error resides in your code, right down to the broken line.

But, you don’t need to take our word for it. Create a Free Airbrake Dev Account and, for the first 30 days, you’ll have unlimited errors and events.

Written By: Alexandra Lindenmuth