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.
Related Articles
- Try, Except, Else and Finally in Python
- ZeroDivisionError Exception in Python
- OverflowError Exception in Python
- ArithmeticError Exception in Python
- KeyError Exception in Python
- LookupError Exception in Python
- StopIteration Exception in Python
- TypeError Exception in Python
- NameError Exception in Python
- FileNotFoundError Exception in Python
- Catch Multiple Exceptions in Python