ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE

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

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

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

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

More Python Programming questions

Exams that ask this topic