ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
adders = [lambda x, n=n: x + n for n in range(3)]
mults = list(map(lambda n: (lambda x: x * n), range(3)))
print([f(10) for f in adders], [g(10) for g in mults])
  1. A. [12, 12, 12] [20, 20, 20]
  2. B. [10, 11, 12] [20, 20, 20]
  3. C. [12, 12, 12] [0, 10, 20]
  4. D. [10, 11, 12] [0, 10, 20]

Correct answer: D. [10, 11, 12] [0, 10, 20]

Both fix the late-binding issue: a default argument captures n's current value, and creating each lambda inside a separate function call (the outer lambda) gives each its own n.

More Python Programming questions

Exams that ask this topic