list of lambda
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() 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']]
so x.upper() will of course return 'C' for all three lambdas:
> 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']]
More information about the Python-list