list of lambda

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

"jena" <jena at> 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

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

>>> l[0]()

> 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
>>> l[0]()
>>> l[1]()
>>> l[2]()


More information about the Python-list mailing list