[Tutor] lambda in a loop

Alan Gauld alan.gauld at freenet.co.uk
Wed Nov 16 23:09:35 CET 2005


--------------------------------
 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




More information about the Tutor mailing list