Find Mistake: Modifying List During Iteration
Find the Mistake Medium
Question
This code skips elements unexpectedly. What is wrong?
Code
nums = [1, 2, 3, 4, 5]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
Hint
Modifying a list while looping over it is dangerous.
Explanation
Removing items from a list while iterating over it causes the iterator to skip elements. After removing 2, the list shifts and 3 is skipped, so 4 is never checked. The fix is to iterate over a copy: for n in nums[:]: or build a new list with a comprehension.
Related Resources
Related Lessons
- Lists
List iteration pitfalls.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.