"jena" <[EMAIL PROTECTED]> 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>



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to