lambda in list comprehension acting funny

Hans Mulder hansmu at xs4all.nl
Wed Jul 11 18:22:06 EDT 2012


On 11/07/12 20:38:18, woooee wrote:
> You should not be using lambda in this case
> .for x in [2, 3]:
> .    funcs = [x**ctr for ctr in range( 5 )]
> .    for p in range(5):
> .        print x, funcs[p]
> .    print

The list is called "funcs" because it is meant to contain functions.
Your code does not put functions in the list, so it doesn't do what
he wants.

He could do:

funcs = []
for i in range(5):
    def f(x):
        return x**i
    funcs.append(f)
print funcs[0]( 2 )
print funcs[1]( 2 )
print funcs[2]( 2 )

.... and it will print 16, 16, 16 for the same reason as the lambda
version.  On the other hand, this does what he wants:

funcs = []
for i in range(5):
    def f(x, i=i):
        return x**i
    funcs.append(f)
print funcs[0]( 2 )
print funcs[1]( 2 )
print funcs[2]( 2 )

The lambda keyword is a red herring.  The question is really about
functions, and how they handle non-local variables.  The good news
is that 'lambda' and 'def' work exactly the same in that regards.
So once you understand the finer points about 'def', you no longer
have a reason to avoid 'lambda'.

Hope this helps,

-- HansM





More information about the Python-list mailing list