ProgrammingModerateTCS NQT · Infosys pattern

What is printed?

What is printed?
a = [1, 2, 3, 4, 5, 6]
for x in a:
    if x % 2 == 0:
        a.remove(x)
print(a)
  1. A. [1, 3, 5, 6]
  2. B. [1, 2, 3, 4, 5, 6]
  3. C. [1, 3, 5]
  4. D. [1, 3, 4, 5]

Correct answer: C. [1, 3, 5]

Removing while iterating shifts later elements left, so the loop skips the element after each removed one. Here 2 is removed (3 skipped), 4 removed (5 skipped), 6 removed – the result looks right only by luck. With [2, 4, 6, 8] the same loop leaves [4, 8]. Iterate over a copy or build a new list.

More Python Programming questions

Exams that ask this topic