ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
fs = []
for i in range(3):
    fs.append(lambda x: x + i)
i = 10
print([f(1) for f in fs])
  1. A. [11, 11, 11]
  2. B. [1, 2, 3]
  3. C. [3, 3, 3]
  4. D. [13, 13, 13]

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

Each lambda looks up the global i when CALLED, not when created. After the loop, i is rebound to 10, so every call returns 1 + 10 = 11.

More Python Programming questions

Exams that ask this topic