ProgrammingHardAccenture pattern

What is printed?

What is printed?
def makeFuncs():
    return [lambda x, n=n: x ** n for n in range(1, 4)]
fns = makeFuncs()
print([f(2) for f in fns])
  1. A. [8, 8, 8]
  2. B. [2, 4, 8]
  3. C. [1, 2, 3]
  4. D. [2, 2, 2]

Correct answer: B. [2, 4, 8]

The default argument n=n captures the current loop value at DEFINITION time for each lambda, avoiding the late-binding trap. So the three lambdas compute 2**1, 2**2, 2**3 = 2, 4, 8.

More Python Programming questions

Exams that ask this topic