List IndexError Exception Handling
IndexError
is an exception that occurs when attempting to access an index outside the valid range of a list.
This exception is raised when an index exceeds the length of the list or when attempting to access an element in an empty list.
For example, attempting to access the 4th element in a list with only 3 elements will raise an IndexError
.
Example of IndexError
fruits = ["apple", "banana", "cherry"]
# IndexError occurs because there is no 4th element
fourth_fruit = fruits[3]
How to Handle IndexError Exceptions?
To prevent an IndexError
, you can either check the length of the list beforehand or use an exception handling.
Example of Checking List Length
fruits = ["apple", "banana", "cherry"]
# Check the length of the list to prevent IndexError
if len(fruits) > 3:
fourth_fruit = fruits[3]
else:
print("The list contains only 3 elements.")
print()
# Using exception handling
try:
fourth_fruit = fruits[3]
except IndexError:
print("An exception has occurred.")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.