IndexError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

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.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. LookupError Exception in Python
  7. StopIteration Exception in Python
  8. TypeError Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python