Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
Closures capture variables, not values, and look them up when called; by then the loop variable is 2. Bind the current value with a default argument, functools.partial or a factory function.
Each lambda refers to the same variable i in the enclosing scope. Python resolves i when the lambda runs, which is after the comprehension finished, so every function sees the final value. Writing lambda i=i: i evaluates i at definition time and stores it as a default, functools.partial(func, i) binds the argument explicitly, and a factory like make_fn(i) creates a new scope for each value. The same late-binding issue appears with callbacks registered in loops, for example in GUI code or task scheduling.