ProgrammingHardInfosys pattern

What is printed?

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

Correct answer: B. [3, 3, 3]

All three lambdas close over the same local variable x. After the loop finishes, x holds its final accumulated value 0+0+1+2=3, so every call returns 3.

More Python Programming questions

Exams that ask this topic