lambda forms within a loop

Michal Ostrowski mostrows at gmail.com
Sat Oct 24 23:33:15 EDT 2009


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.

The expected output of this code is

11
12
11
12

However, what we get instead is

12
12
11
12

The problem is that the two functions returned by MakeLambdaBad() are
apparently the same, but the functions returned by MakeLambdaGood()
are different.

Can anyone explain why this would/should be the case?

--
Michal Ostrowski
mostrows at gmail.com


def MakeLambdaGood():
  def DoLambda(x):
     return lambda q: x + q
  a = []
  for x in [1,2]:
     a.append(DoLambda(x))
  return a

def MakeLambdaBad():
  a = []
  for x in [1,2]:
     a.append(lambda q:  x + q)
  return a

[a,b] = MakeLambdaBad()
print a(10)
print b(10)
[a,b] = MakeLambdaGood()
print a(10)
print b(10)



More information about the Python-list mailing list