ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def outer():
    res = []
    for i in range(3):
        res.append(lambda: i)
    return [f() for f in res]
def outer2():
    return [(lambda j: (lambda: j))(i) for i in range(3)]
print(outer(), [f() for f in outer2()])
  1. A. [0, 1, 2] [0, 1, 2]
  2. B. [2, 2, 2] [2, 2, 2]
  3. C. [0, 1, 2] [2, 2, 2]
  4. D. [2, 2, 2] [0, 1, 2]

Correct answer: D. [2, 2, 2] [0, 1, 2]

Lambdas capture the variable i, not its value at creation, so every call sees the final i = 2. In outer2 each lambda is created inside a function whose argument fixes the value per iteration.

More Python Programming questions

Exams that ask this topic