Python coding · Write code
Removing items while looping over a list
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
We want to remove all even numbers. What does this print, and why? Show two correct ways.
nums = [2, 4, 5, 6, 8, 9]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
Then
Follow-ups the interviewer asks next
- What happens if you do the same with a dict?
- Which fix changes the list in place, so other references see it?
- What's the time cost of
removein a loop?
The answer
What a strong answer covers
- Prints
[4, 5, 8, 9]. Removing an item shifts the rest left, but the loop's position moves on, so the item right after each removed one is skipped. - Fixes: a new list
[n for n in nums if n % 2]; in placenums[:] = [...]; loop over a copy (for n in nums[:]); or walk backwards by index. - A dict or set raises
RuntimeError: dictionary changed size during iteration. removesearches from the start each time, so the loop is O(n²).
The red pen
Common traps
Avoid:answering [5, 9]; "Python handles it".
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.