Help with lambda
Arnaud Delobelle
arnodel at googlemail.com
Thu Feb 18 07:47:31 EST 2010
lallous <elias.bachaalany at gmail.com> writes:
> Hello,
>
> I am still fairly new to Python. Can someone explain to me why there
> is a difference in f and g:
>
> def make_power(n):
> return lambda x: x ** n
>
> # Create a set of exponential functions
> f = [lambda x: x ** n for n in xrange(2, 5)]
> g = [make_power(n) for n in xrange(2, 5)]
>
> print f[0](3), f[1](3)
> print g[0](3), g[1](3)
>
>
> I expect to have "f" act same like "g".
>
> Thanks
It's a FAQ! Except I don't think it's in the official Python FAQ, but
it ought to be.
The reason (very quickly) is that each time you call make_power() you
create a new name 'n' which is bound to a different value each time,
whereas in f:
[lambda x: x ** n for n in xrange(2, 5)]
The 'n' is the same name for each of the lambda functions and so is
bound to the same value, which by the end of the loop is 4. So each of
the lambdas in the list f is the same as:
lambdsa x; x**4
after the end of the list comprehension.
The usual fix for this is to change f to:
f = [lambda x, n=n: x ** n for n in xrange(2, 5)]
I'll let you think why this works.
HTH
--
Arnaud
More information about the Python-list
mailing list