Data Structures & AlgorithmsVery hardTCS NQT Digital · Product Company SDE

Problem: What does this snippet print? fs=[lambda: i for i in range(3)] print([f() for f in fs])

  1. A. [2, 2, 2]
  2. B. [0, 1, 2]
  3. C. [1, 2, 3]
  4. D. [0, 0, 0]

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

Each lambda captures the variable i, not its value at creation, so all three see the final value of the loop variable. Binding i as a default argument would give 0, 1, 2 instead.

More Coding Interview Problems questions

Exams that ask this topic