understand and fix indexerror in python

Understand and Fix IndexError in Python

If you are working with Python, you may have encountered an IndexError at some point. This error occurs when you try to access an index that is out of range for a list, tuple, or string. It can be frustrating to encounter this error, especially if you are not sure how to fix it.

understand and fix indexerror in python

In this tutorial, we will explain what an IndexError is, why it occurs, and how to fix it. We will provide examples of common scenarios where an IndexError can occur and walk you through step-by-step solutions to resolve the issue. By the end of this tutorial, you will have a better understanding of how to handle IndexError in your Python code.

Understanding IndexError in Python

Let’s understand what IndexError is in Python in detail.

Why does the IndexError occur?

In Python, IndexError is a common error that occurs when you try to access an index that is out of range of a list, tuple, or string. Let’s reproduce this error.

# create a list
ls = [1, 2, 3]
# print element at index 3
print(ls[3])

Output:

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[1], line 4
      2 ls = [1, 2, 3]
      3 # print element at index 3
----> 4 print(ls[3])

IndexError: list index out of range

We get an IndexError: list index out of range because the index 3 is out of range of indices in the list ls. Since the list ls has three values, the max index we can access in the list is 2 (sequences are indexed from 0 in Python), if you try to access an index outside the range of indices, you’ll get an IndexError.

This applies to other ordered iterables as well such as strings, tuples, etc.

# create a string
s = "cat"
# get character at index 3
print(s[3])

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[2], line 4
      2 s = "cat"
      3 # get character at index 3
----> 4 print(s[3])

IndexError: string index out of range

Here, we get the IndexError: string index out of range as we are trying to access an index that is not present in the string.

# create a tuple
tup = (1, 2, 3)
# get element at index 3
print(tup[3])

Output:

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[3], line 4
      2 tup = (1, 2, 3)
      3 # get element at index 3
----> 4 print(tup[3])

IndexError: tuple index out of range

Similarly, we get IndexError: tuple index out of range.

IndexError with negative Indexes

Python also allows negative indexing of sequences. Negative indexing lets you to access elements of a sequence (such as a string, list, or tuple) from the end, rather than from the beginning.

For example, in the list ls = [1, 2, 3], you can access the last element using ls[-1].

# create a list
ls = [1, 2, 3]
# last element
print(ls[-1])
# second last element
print(ls[-2])

Output:

3
2

You can also get IndexError when using a negative index. For example, in the above list, if you try to access the element at index -4, you’ll get an IndexError.

# create a list
ls = [1, 2, 3]
print(ls[-4])

Output:

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[11], line 3
      1 # create a list
      2 ls = [1, 2, 3]
----> 3 print(ls[-4])

IndexError: list index out of range

We get IndexError: list index out of range. This is because here we are trying to access the 4th element in the list from the end and the list only has 3 elements.

How to Fix IndexError in Python

Now that we know what IndexError is and why it occurs in Python, let’s see how we can fix or avoid it such that our code runs error free.

We can take the following approaches to fix IndexError in Python.

Checking the Index Range using If-Else statement

One way to fix the IndexError is to check the index range before accessing the element. You can use an if-else statement to check if the index is within the range of the list or array. If the index is within the range, you can access the element, otherwise, you can print an error message. Here’s an example:

ls = [1, 2, 3]

index = 3

if -len(ls) <= index < len(ls):
    print(ls[index])
else:
    print("Index out of range")

Output:

Index out of range

Note that in the above code, we are checking whether the index lies in the range [-len(ls), len(ls)) which makes the code robust to check even negative indices.

Using Try-Except Block

Another way to fix the IndexError is to use a try-except block. In this approach, you try to access the element at the given index and catch the IndexError exception if it occurs. Here’s an example:

ls = [1, 2, 3]

index = 3

try:
    print(ls[index])
except IndexError:
    print("Index out of range")

Output:

Index out of range

Here, we use exception handling to manage the IndexError, in the above code ls[index] will raise an IndexError in the index is outside the index range of ls. We’re handling this IndexError in the except block and printing “Index out of range”.

Key Takeaways

In this tutorial, we explored what IndexError is in Python, why does it occur, and how we can avoid it. The following are the key takeaways from this tutorial.

  • An IndexError occurs when you try to access an index that is out of range in a list, tuple, or string.
  • You can fix an IndexError by ensuring that the index you are trying to access is within the range of the sequence.
  • Remember that Python indexing starts at 0, so the first element in a sequence has an index of 0, not 1.
  • Be careful when using negative indices, as they count from the end of the sequence and can also result in an IndexError if they are out of range.
  • You can also use exception handling to catch and handle IndexError in your code.

You might also be interested in –

Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top