Data Structures & AlgorithmsVery hardTCS NQT Digital · Infosys

Problem: Consider the list a = [2, 4, 6, 8]. The loop 'for x in a: if x % 2 == 0: a.remove(x)' is run. What is the list a afterwards?

  1. A. [4, 6, 8]
  2. B. [2, 4, 6, 8]
  3. C. []
  4. D. [4, 8]

Correct answer: D. [4, 8]

Removing items while iterating shifts the remaining elements, so the iterator skips the element after each removal. Only every other element is removed, which leaves the list non-empty.

More Coding Interview Problems questions

Exams that ask this topic