A “List index out of range” error occurs when trying to access an index that is outside the valid range of the list. Here are two examples:
Example 1:
numbers = [1, 2, 3] try: value = numbers[3] print(f"The value at index 3 is: {value}") except IndexError: print("List index out of range!")
Output:
List index out of range!
Example 2:
fruits = ['apple', 'banana'] try: value = fruits[2] print(f"The value at index 2 is: {value}") except IndexError: print("List index out of range!")
Output:
List index out of range!