Skip to content Skip to sidebar Skip to footer

Unexpected Behavior With A List Of Functions Defined Via Lambda

I'd like to understand why the two prints below produce different results: f = [lambda x: x**2, lambda x: x+100] f_new = [lambda x: fi(x) for fi in f] print( [fi(2) for fi in f] )

Solution 1:

The two lambdas in f_new actually call the same function.

This is because the list is formed of lambdas that capture the fi variable (at compile time) but do not actually execute the function. So, when the list runs through the generator ... for fi in f the lambdas that are produce all use the captured variable fi and end up with the same function pointer (i.e. the last one in f)

You would need to consume the current value of fi in the comprehension in order to avoid this capture side effect:

f_new = [(lambda fn:lambda x: fn(x))(fi) forfiin f]
print( [fi(2) forfiin f_new] )
[4, 102]

Post a Comment for "Unexpected Behavior With A List Of Functions Defined Via Lambda"