list of lambda

Fredrik Lundh fredrik at pythonware.com
Sat Nov 12 00:48:38 CET 2005


"jena" <jena at vlakosim.com> wrote:

> when i create list of lambdas:
> l=[lambda:x.upper() for x in ['a','b','c']]
> then l[0]() returns 'C', i think, it should be 'A'

the "x" variable contains "c" when you leave the loop:

>>> l=[lambda:x.upper() for x in ['a','b','c']]
>>> x
'c'

so x.upper() will of course return 'C' for all three lambdas:

>>> l[0]()
'C'

> it is OK or it is bug?

it's not a bug.  free variables bind to names, not objects.

> can i do it correctly simplier than with helper X class?

bind to the object instead of the name:

>>> l=[lambda x=x:x.upper() for x in ['a','b','c']]
>>> x
'c'
>>> l[0]()
'A'
>>> l[1]()
'B'
>>> l[2]()
'C'

</F>






More information about the Python-list mailing list