list of lambda
Bengt Richter
bokr at oz.net
Fri Nov 11 23:39:18 EST 2005
On 11 Nov 2005 18:28:22 -0800, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>jena <jena at vlakosim.com> writes:
>> l=[lambda:x.upper() for x in ['a','b','c']]
>> then l[0]() returns 'C', i think, it should be 'A'
>
>Yeah, this is Python late binding, a standard thing to get confused
>over. You want:
>
> l = [lambda x=x: x.upper() for x in ['a', 'b', 'c']]
or if you want the upper() eagerly (and do it only once each,
in case of multiple lambda calls)
l = [lambda x=x.upper():x for x in ['a', 'b', 'c']]
>>> l = [lambda x=x.upper():x for x in ['a', 'b', 'c']]
>>> for lamb in l: print lamb.func_defaults[0],'=?=',lamb()
...
A =?= A
B =?= B
C =?= C
Regards,
Bengt Richter
More information about the Python-list
mailing list