Back to questions
MiddleCodeOccasional
What does this list of lambdas print?
Predict what the comprehension prints.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])Determine the output and explain.
[2, 2, 2]. The closures capture the variable i, not its value at creation time (late binding). By the time the lambdas run, the loop has finished and i == 2. Fix by binding per-iteration with a default arg: [lambda i=i: i for i in range(3)].
- Believing closures capture the value rather than the variable
- Expecting
[0, 1, 2]from value-at-creation semantics - Not knowing the default-argument binding fix
- Why does a default-argument binding capture the current value of
i? - How does this differ between a generator expression and a list comprehension?