Skip to the page

Python coding · Write code

Removing items while looping over a list

The 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

  1. What happens if you do the same with a dict?
  2. Which fix changes the list in place, so other references see it?
  3. What's the time cost of remove in 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 place nums[:] = [...]; loop over a copy (for n in nums[:]); or walk backwards by index.
  • A dict or set raises RuntimeError: dictionary changed size during iteration.
  • remove searches 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 voice

Practise 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.

Start your free interview