Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of functions in python

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?

like image 496
D R Avatar asked Dec 13 '10 05:12

D R


2 Answers

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
like image 99
John La Rooy Avatar answered Sep 21 '22 01:09

John La Rooy


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.

like image 43
luispedro Avatar answered Sep 20 '22 01:09

luispedro