Python IndexError Exception
Example
A IndexError
occurs if you try access a list item with an index that does not exist:
x = ["apple", "banana", "cherry"]
print(x[5])
Try it Yourself »
Definition and Usage
The IndexError
exception occurs when you use an index on a sequence, like a
list or a tuple, and the index is out of range.
You can handle the IndexError
in a try...except
statement, see the example below.
Exception Handling
Example
Handling the IndexError
in a try...except
statement:
x = ["apple", "banana", "cherry"]
try:
print(x[5])
except IndexError:
print("You are trying to access an item that does not exist!")
except:
print("Something else went wrong")
Try it Yourself »