Listing 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 expect it to be equivalent

basis = [ (lambda x: 0*x), (lambda x: 1*x), (lambda x: 2*x) ]
print basis[0](1)

However, while the second snippet prints 0, what I expect is the first fingerprints of 2. What is wrong with the first snippet of code and why doesn’t it behave as expected?

+5
source share
4 answers

You can use the default parameter to create a loop on n

>>> basis = [ (lambda x,n=n: n*x) for n in [0, 1, 2] ]     
>>> print basis[0](1)
0
+8
source

Because he "passes by name."

, lambda, n*x: x 1 ( ), n ( 2). , 2.

+3

, n - , , . n 2 , 2 n.

-, :

basis = [ (lambda x,n=n: n*x) for n in [0, 1, 2] ]
print basis[0](1) 

, n n=n , .

+2

I want to help with understanding the commentary from Karl Knechtel (December 13-13 at 7:32). The following code shows how using a generator, the original lambda definition gives the result, but does not use a list or tuple:

>>> #GENERATOR
... basis = ( (lambda x: n*x) for n in [0, 1, 2] )  
>>> print(type(basis))
<type 'generator'>
>>> basis = ( (lambda x: n*x) for n in [0, 1, 2] ) 
>>> print([x(3) for x in basis])
[0, 3, 6]
>>> #TUPLE
... basis = tuple( (lambda x: n*x) for n in [0, 1, 2] )
>>> print(type(basis))
<type 'tuple'>
>>> print([x(3) for x in basis])
[6, 6, 6]
>>> #LIST
... basis = list( (lambda x: n*x) for n in [0, 1, 2] )
>>> print(type(basis))
<type 'list'>
>>> print([x(3) for x in basis])
[6, 6, 6]
>>> #CORRECTED LIST
... basis = list( (lambda x, n=n: n*x) for n in [0, 1, 2] )
>>> print(type(basis))
<type 'list'>
>>> print([x(3) for x in basis])
[0, 3, 6]
0
source

All Articles