Quick Answer
Handle list boundary issues safely.
Understanding the Issue
IndexError occurs when accessing list elements beyond their bounds. Common in loops or when assuming fixed list lengths. Python uses zero-based indexing (first element is index 0). Negative indices count from the end (-1 is last element).
The Problem
This code demonstrates the issue:
Python
Error
colors = ["red", "green"]
print(colors[5]) # Fails
print(colors[-3]) # Fails
The Solution
Here's the corrected code:
Python
Fixed
# Solution 1: Boundary checks
if len(colors) > 5:
print(colors[5])
# Solution 2: Safe access
try:
item = colors[5]
except IndexError:
item = default_value
# Solution 3: Use get() for dict-like behavior
item = colors[5] if len(colors) > 5 else None
Key Takeaways
Always validate indices before access.