ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def make():
    acc = []
    for i in range(3):
        def f(x, i=i):
            return x * i
        acc.append(f)
        acc.append(lambda x: x + i)
    return acc
fs = make()
print([f(10) for f in fs])
  1. A. [0, 12, 10, 12, 20, 12]
  2. B. [0, 10, 10, 11, 20, 12]
  3. C. [20, 12, 20, 12, 20, 12]
  4. D. [0, 10, 10, 10, 20, 10]

Correct answer: A. [0, 12, 10, 12, 20, 12]

A default argument is evaluated once, when the def statement runs, so each f freezes its own i (0, 1, 2) and returns 0, 10, 20. The lambdas have no default: they look i up in make's scope when they are finally called, after the loop has ended with i = 2, so all three return 12. Interleaved: [0, 12, 10, 12, 20, 12]. The option [0, 10, 10, 11, 20, 12] assumes the lambdas also capture the value at creation time.

More Python Programming questions

Exams that ask this topic