Accessing a list, tuple, or string with an out-of-range index.
An IndexError is raised when you try to access an element in a sequence (list, tuple, string) using an index that is outside the valid range. Python sequences are 0-indexed, so a list with 3 elements has valid indices 0, 1, and 2. Using index 3 or any negative index below `-3` will raise this error.
This commonly happens when: using a hardcoded index that exceeds the list length, using the wrong loop variable for indexing, trying to access the 'last + 1' element, miscalculating the length-based index, or receiving a smaller-than-expected list from an API or function.
1fruits = ["apple", "banana", "cherry"]2# List has 3 elements: index 0, 1, 23 4# Trying to access index 3 (out of range)5print(fruits[3])1fruits = ["apple", "banana", "cherry"]2 3# Fix 1: Use the correct index4print(fruits[2]) # "cherry"5 6# Fix 2: Use negative indexing to access the last element7print(fruits[-1]) # "cherry" (last element)8 9# Fix 3: Check the length before accessing10index = 311if index < len(fruits):12 print(fruits[index])13else:14 print(f"Index {index} is out of range. List has {len(fruits)} elements.")15 16# Fix 4: Use a safe get with exception handling17try:18 print(fruits[3])19except IndexError:20 print("Index is out of range!")Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The list `fruits` contains 3 elements at indices `0`, `1`, and `2`. Accessing `fruits[3]` goes one past the end of the list, causing `IndexError: list index out of range`. Python does not allow access beyond the last valid index.