[Tutor] lambda in a loop

Fred Lionetti lordvader at gmail.com
Wed Nov 16 21:32:21 CET 2005


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


More information about the Tutor mailing list