Hi everyone,

 If I have this code:

--------------------------------
 def doLambda(val):
   print "value 2:", val

 commands = []
 for value in range(5):
   print "value 1:", value
   commands.append(lambda:doLambda(value))

 for c in commands:
   c()
----------------------------------

 my output is:
 value 1: 0
 value 1: 1
 value 1: 2
 value 1: 3
 value 1: 4
 value 2: 4
 value 2: 4
 value 2: 4
 value 2: 4
 value 2: 4

 Obviously, the lambda is using "value" at the end of the loop (4),
rather than what I want, "value" during the loop (0,1,2,3).  Is there
any *simple* way around this?  I'd prefer not to use a separate array
with all the values ( i.e.
commands.append(lambda:doLambda(values[commands.index(c)])) ) if
possible.

 Thanks,
 Fred
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to