Bugs
Python IndexError: List Index Out of Range
The IndexError: list index out of range error happens when code tries to access a list element using an index that doesn't exist — usually an off-by-one error.
❌ Off-by-One Error
items = ['apple', 'banana', 'cherry']
for i in range(len(items) + 1): # Bug: one too far!
print(items[i])✅ Correct Loop
items = ['apple', 'banana', 'cherry']
for item in items: # Iterate directly — no index math
print(item)
# Or if you need index:
for i, item in enumerate(items):
print(i, item)💡
Pro tip: Prefer iterating directly over a list with `for item in items` to eliminate index arithmetic entirely.
Paste this code into LearnCodeGuide
Detect Python vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Python Code →