ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

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

Correct answer: C. [1, 2, 3, 4]

Removing an item shifts the rest left, so the iterator skips the second 2 that moved into the current position. One 2 remains in the result.

More Python Programming questions

Exams that ask this topic