Re: lambda forms within a loop

2009-10-25 Thread Paul Rubin
Michal Ostrowski writes: > def MakeLambdaBad(): > a = [] > for x in [1,2]: > a.append(lambda q: x + q) > return a The problem here is that x is a free variable in the lambdas that you put in a. When you actually evaluate those lambdas, they use whatever the value of x happens to be a

Re: lambda forms within a loop

2009-10-25 Thread Scott David Daniels
Michal Ostrowski wrote: ... [a,b] = MakeLambda() print a(10) print b(10) Here is yet another way to solve the problem: import functools def AddPair(x, q): return x + q a, b = [functools.partial(AddPair, x) for x in [1, 2]] print a(10) print b(10) Or even, since the

Re: lambda forms within a loop

2009-10-25 Thread Duncan Booth
Michal Ostrowski wrote: > def MakeLambdaBad(): > a = [] > for x in [1,2]: > a.append(lambda q: x + q) > return a Two things to remember when using lambda: 1. You can always replace lambda with one line function returning the same result. The only difference is that you have to give

Re: lambda forms within a loop

2009-10-24 Thread Lawrence D'Oliveiro
In message , Michal Ostrowski wrote: > def MakeLambdaBad(): > a = [] > for x in [1,2]: > a.append(lambda q: x + q) > return a Here's another form that should work: def MakeLambdaGood2() : a = [] for x in [1, 2] : a.append((lambda x : lambda q : x + q)

Re: lambda forms within a loop

2009-10-24 Thread Chris Rebert
On Sat, Oct 24, 2009 at 8:33 PM, Michal Ostrowski wrote: > The snippet of code below uses two functions to dynamically create > functions using lambda. > Both of these uses should produce the same result, but they don't. > def MakeLambdaGood(): > def DoLambda(x): > return lambda q: x + q >