I have the following python code that generates a list of anonymous functions:
basis = [ (lambda x: n*x) for n in [0, 1, 2] ]
print basis[0](1)
I would have expected it to be equivalent to
basis = [ (lambda x: 0*x), (lambda x: 1*x), (lambda x: 2*x) ]
print basis[0](1)
However, whereas the second snippet prints out 0 which is what I would expect, the first prints 2. What's wrong with the first snippet of code, and why doesn't it behave as expected?
You can use a default parameter to create a closure on n
>>> basis = [ (lambda x,n=n: n*x) for n in [0, 1, 2] ]
>>> print basis[0](1)
0
Because it's "pass by name".
That is, when the lambda
is run, it executes n*x
: x
is bound to 1
(it is a parameter), n
is looked up in the environment (it is now 2). So, the result is 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With