Problem
Handling an IndexError when accessing an invalid list index.
Code
my_list = [1, 2, 3]
value = my_list[5]
Error
IndexError: list index out of range
Issue
The error occurs because you are trying to access an index (5) that does not exist in the list. The list has only three elements with indices 0, 1, and 2.
Solution
Before accessing the list index, check if the index is within the valid range.
Fixed Code
my_list = [1, 2, 3]
index = 5
if 0 <= index < len(my_list):
value = my_list[index]
else:
print("Error: Index out of range.")
Alternatively, you can use a try-except block to catch the error.
Alternative Code
my_list = [1, 2, 3]
try:
value = my_list[5]
except IndexError:
print("Error: Index out of range.")