Predict the output · Python

Late-Binding Closures

Medium Predict the output Seen at Google, Spotify

What does this print?

What does this print?

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
  1. [0, 1, 2]
  2. [2, 2, 2]
  3. [3, 3, 3]
  4. NameError

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

[2, 2, 2]

Each lambda refers to the variable i of the comprehension's scope and reads it when called. By then the loop has finished with i == 2.

Bind the current value with a default argument (lambda i=i: i) or use functools.partial.