ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def make():
    fs = []
    for i in range(3):
        fs.append(lambda: i)
    i = "z"
    return fs
print([f() for f in make()])
  1. A. [2, 2, 2]
  2. B. ['z', 'z', 'z']
  3. C. [0, 1, 2]
  4. D. ['z', 1, 2]

Correct answer: B. ['z', 'z', 'z']

All three lambdas close over the same cell for the local variable i. That cell is reassigned to 'z' before make returns, so every closure reads 'z'.

More Python Programming questions

Exams that ask this topic