The Secret Life of Python: The Loophole
Source: Dev.to
The trap of modifying a list while iterating over it (and how to fix it)
Timothy was staring at a list of sensor data on his screen.
“I told it to remove the errors. I wrote the code explicitly. But it keeps missing them.”
He had a list of temperature readings where any value below zero was considered an error. His loop looked like this:
# Timothy's "Cleanup" Loop
temperatures = [10, -5, -2, 15, 20]
for temp in temperatures:
if temp = 0]
print(f"Cleaned List: {clean_temperatures}")
Output
Cleaned List: [10, 15, 20]
This approach avoids in‑place modification altogether and is often faster and clearer.
Margaret’s Cheat Sheet
- The Trap: Never add or remove items from a list while looping over it.
- The Symptom: Skipped items (when removing) or infinite loops (when adding).
- The Reason: Changing the list length shifts indices, but the loop counter continues marching forward.
Fixes
- Iterate over a copy:
for item in my_list[:](quick fix). - List comprehension:
[x for x in my_list if condition](best for filtering). - Iterate backwards:
for item in reversed(my_list):(advanced; useful when you must modify in‑place without copying).