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

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

Close but not quite. Try:

commands.append(lambda v=value:doLambda(v))

value is a local variable in doLambda so when it executes it uses 
whatever the global 'value' is set at, which at the end of the loop 
will be 4. By using the default argument and passing that you freeze 
the value at whatever it is at the time of setting (a fortuitous 
by-product of how default parameters work!)

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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

Reply via email to