ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
  1. A. NameError
  2. B. [0, 1, 2]
  3. C. [2, 2, 2]
  4. D. [0, 0, 0]

Correct answer: C. [2, 2, 2]

Closures bind late: each lambda looks up i when it is CALLED, and by then the comprehension has finished with i = 2. Writing lambda i=i: i fixes the value at creation time.

More Python Programming questions

Exams that ask this topic