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
mostr...@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)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to