Something is rotten in Denmark...

harrismh777 harrismh777 at charter.net
Tue May 31 02:48:05 EDT 2011


>>> fs=[]
>>> fs = [(lambda n: i + n) for i in range(10)]
>>> [fs[i](1) for i in range(10)]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]         <=== not good

     ( that was a big surprise! . . . )
     ( let's try it another way . . . )


>>> fs =[]
>>> def g(i): return (lambda n: i + n)
>>> fs = [g(i) for i in range(10)]
>>> [fs[i](1) for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      (aaah,  that's better . . . )
      (hmmm, let's try another . . . )


>>> fs =[]
>>> for i in range(10):
	fs.append(lambda n, i=i: i + n)
>>> [fs[i](1) for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      (aaaah, that works too . . . )
      (... and another... )


>>> fs=[]
>>> fs = [(lambda n, i=i: i + n) for i in range(10)]
>>> [fs[i](1) for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      (great! . . . )
      (now then,  what's wrong with this picture ?)

      lambda?  closure?  scope?   bug?

      What is going on with the binding in the first construct... this 
seems to reduce the usefulness of lambda to a considerable extent?





kind regards,
m harris




More information about the Python-list mailing list