Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Find the bug: even values are removed from a list while iterating over that same list.

Problem: Find the bug: even values are removed from a list while iterating over that same list.
nums = [2, 4, 4, 6, 5, 8]
for x in nums:
    if x % 2 == 0:
        nums.remove(x)
print(nums, [x for x in [2, 4, 4, 6, 5, 8] if x % 2])
What is printed?
  1. A. [4, 4, 6, 5] [5]
  2. B. [4, 6, 5] [5]
  3. C. [6, 5] [5]
  4. D. [5] [5]

Correct answer: B. [4, 6, 5] [5]

The for loop walks by index while remove() shifts later elements left, so the element after each removed one is skipped. Index 0: remove 2 → [4, 4, 6, 5, 8]; index 1 is now the second 4 → remove (the first 4) → [4, 6, 5, 8]; index 2 is 5; index 3 is 8 → remove → [4, 6, 5]. Build a new list (comprehension) or iterate over a copy. remove() is also O(n) per call.

More Coding Interview Problems questions

Exams that ask this topic