list of lambda

jena jena at vlakosim.com
Fri Nov 11 18:17:59 EST 2005


hello,
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'

my workaround is to define helper class with __call__ method:
class X:
    def __init__(self,s): self.s=s
    def __call__(self): return self.s.upper()
l=[X(x) for x in ['a','b','c']]

now it is correct, l[0]()=='A'

it is OK or it is bug?
can i do it correctly simplier than with helper X class?

thanks
Honza Prochazka



More information about the Python-list mailing list