Data Structures & AlgorithmsVery hardTCS NQT Digital · closures

Problem: What does the following print?

Problem: What does the following print?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
  1. A. [0, 1, 2]
  2. B. [0, 0, 0]
  3. C. [2, 2, 2]
  4. D. [1, 2, 3]

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

Lambdas capture the variable i, not its value at creation, so after the loop every function sees i = 2. Binding it with a default argument fixes this.

More Coding Interview Problems questions

Exams that ask this topic