ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE

What does the following Python 3 code print? fs = [lambda: i * 5 for i in range(3)] print([f() for f in fs])

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

Correct answer: D. [10, 10, 10]

Closures capture the variable i, not its value; after the loop i equals n−1, so every lambda sees that final value. Output: [10, 10, 10].

More Python Programming questions

Exams that ask this topic