IndexError Exception in Python

Handle Index error exception in Python using the try-except block.

IndexError Exception in Python
Index error in Python

The IndexError exception in Python means that you are trying to access an index that doesn’t exist. For example you are trying to access the 5th index of a list, but there are only 4 elements present. It is part of the LookupError Exception class.

This error can happen with any object that is indexable, like - Lists, Tuples, Strings etc.


Example 1

Code

x = [1, 2, 3, 4]

print(x[5])

Output

Traceback (most recent call last):
  File "some_file_location", line 3, in <module>
    print(x[5])
IndexError: list index out of range

You can handle the above exception using the IndexError exception class.


Example 2

Code/Output

# lists
x = [1, 2, 3, 4]
try:
    print(x[10])
except IndexError as e:
    print(f"{e}")
    
>>> list index out of range
    
# strings
x = "Pylenin"
try:
    print(x[10])
except IndexError as e:
    print(f"{e}")

>>> string index out of range

# tuples
x = (1, 2, 3, 4)
try:
    print(x[10])
except IndexError as e:
    print(f"{e}")

>>> tuple index out of range

Use the IndexError Exception class, when you are working with indexable objects like strings, lists and Tuples.

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe