Python IndexError – Tutorial with Examples

Python IndexError - Tutorial with Examples

IndexError is an error in python that is raised when trying to access a non-existent index of a list, string or any sequence data type. In simple words, this error occurs when we try to access an index element beyond the range of possible indices of a sequence. In this article, we will look at the various scenarios under which we can run into an IndexError in Python and understand how to handle this error through examples.

Example 1: Negative Index Value

In Python, sequence data types such as lists and strings use zero-based indexing, meaning that the first element of a sequence starts at index 0. Negative indexing is also allowed in Python, where -1 refers to the last element of the sequence.

colors = ['red', 'green', 'blue']
print (colors[-4])

The code above would try to access the element at index -4 of colors, which does not exist in the list. An IndexError exception would be raised as a result.

<strong>Output:</strong>
IndexError: list index out of range

To handle this error, we can check if the index is negative and if it is, add the length of the sequence to it.

colors = ['red', 'green', 'blue']
n = -4
if n < 0:
    n += len(colors)
print(colors[n])

The code above handles the error by adding the length of the colors list to the negative index value, converting it to a positive index value. As a result, the code prints the element at index 0 of the colors list.

<strong>Output:</strong>
red

Example 2: Out of Range Index Value

If we try to access an index value greater than or equal to the length of the sequence, an IndexError is raised.

colors = ['red', 'green', 'blue']
print(colors[3])

The code above would try to access the element at index 3 of colors, which does not exist in the list. An IndexError exception would be raised as a result.

<strong>Output:</strong>
IndexError: list index out of range

We can handle this error by checking if the index is greater than or equal to the length of the sequence, and if it is, print an error message.

colors = ['red', 'green', 'blue']
n = 3
if n >= len(colors):
    print('Index out of range')
else:
    print(colors[n])

The code above handles the error by checking if the index value is greater than or equal to the length of the colors list, and if it is, prints an error message. Otherwise, it prints the element at the specified index.

<strong>Output:</strong>
Index out of range

Example 3: Slicing

Python allows us to access a range of elements in a sequence by slicing it, where we can specify the start and end indices of the range we want to access. When using slicing, an IndexError would be raised if we try to access an index value that does not exist in the sequence.

colors = ['red', 'green', 'blue']
print(colors[1:4])

The code above tries to access an element with index 4, which does not exist in the colors list. As a result, an IndexError exception would be raised.

<strong>Output:</strong>
IndexError: list index out of range

We can handle this error by adjusting the slice range to only include the valid indices of the sequence.

colors = ['red', 'green', 'blue']
print(colors[1:3])

The code above only includes the valid indices of the colors list in the slice range, and as a result, the code prints the second and third elements of the list.

<strong>Output:</strong>
['green', 'blue']

Conclusion

In this article, we saw how an IndexError can be raised when trying to access a non-existent index of a sequence in Python. We also learned some ways to handle this error by checking for negative or out of range index values, and adjusting the slice range when using slicing. It is important to handle this error in your code to prevent your program from crashing due to an unhandled exception.

Leave a Reply

Your email address will not be published. Required fields are marked *