The Late-Binding Lambda Trap

Hard ⏱ 18 min 34% acceptance ★★★★☆ 4.4
A classic bug: [lambda x: x * i for i in range(3)] produces three lambdas that ALL multiply by 2, because i is looked up when called, not when defined. Write make_multipliers(n) returning a list of n lambdas where the k-th correctly multiplies by k — fix the trap with a default argument.

Examples

Example 1
Input
funcs = make_multipliers(3); [f(10) for f in funcs]
Output
[0, 10, 20]
Explanation

Each lambda captured its own k (0, 1, 2) instead of sharing the final value.

Constraints

  • Return exactly n callables.
  • The fix must use a default-argument capture (k=k) or an inner factory.

Topics

Lambda & Functionalclosureslate binding

Companies

GoogleMetaMicrosoft

Hints

Hint 1

lambda x, k=k: x * k freezes k at definition time.

Hint 2

Without it, all closures share the loop variable.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.