ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
counters = []
for i in range(3):
    j = i * 2
    counters.append(lambda: j)
print([c() for c in counters])
  1. A. [0, 2, 4]
  2. B. [4, 4, 4]
  3. C. [0, 0, 0]
  4. D. [2, 2, 2]

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

Every lambda closes over the same variable j, which keeps being reassigned each iteration (0, 2, 4). After the loop ends, j holds its last value, 4, so all three closures return 4.

More Python Programming questions

Exams that ask this topic