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])
[0, 1, 2]
[2, 2, 2]
[3, 3, 3]
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.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium