ProgrammingHardPython · GATE DA · Advanced

What is printed?

What is printed?
funcs = []
for i in range(3):
    funcs.append(lambda x=i: x * 10)
    funcs.append(lambda: i * 10)
print([f() for f in funcs])
  1. A. [0, 0, 10, 10, 20, 0]
  2. B. [0, 20, 10, 20, 20, 20]
  3. C. [0, 0, 10, 10, 20, 20]
  4. D. [0, 20, 10, 10, 20, 0]

Correct answer: B. [0, 20, 10, 20, 20, 20]

Default arguments freeze i at definition (0, 10, 20), but the plain lambdas read the global i at call time, when the loop has left i = 2 (20 each).

More Python Programming questions

Exams that ask this topic