BugLab006 / 020up to 100
closuresfunctionsscopehard

Closure Trap

The function make_multipliers(n) should return a list of n functions, where the i-th function multiplies its argument by i.

So make_multipliers(4)[2](5) should return 10 (2 × 5). But every single function in the list behaves identically — they all multiply by the same number.

This is one of Python's most infamous gotchas. The code looks right. But it isn't.

# your fix
+ must use lambda
+ must use for
hint 2after hint 1
hint 3after hint 2
solution

Read the code. Before running anything: what does the last line below give?

def make_multipliers(n):
multipliers = []
for i in range(n):
multipliers.append(lambda x: x * i)
return multipliers
>>> make_multipliers(3)[0](10)