February 22nd, 2004, 06:40 AM
Making closures in loop ?
I want to create a list of functions with something like:
closures = [lambda x: i*x for i in range(10)]
closures = 0*x
closures = 1*x
closures = 2*x
closures = 9*x
For some reason, all elements seem to bind the last value of i, that is closures[j] = 9*x for all j, not only 9. Any ideas of why does this happen, and how should I make it work as intended ?
February 22nd, 2004, 06:47 AM
February 22nd, 2004, 07:10 AM
You can get it to work the way you want by passing in i as a default parameter, i.e.:
This was the standard way to simulate closures in Python prior to 2.1, when it did not have the new scoping rules.
>>> closures = [lambda x, i=i: i*x for i in range(10)]
Dave - The Developers' Coach
February 22nd, 2004, 12:28 PM
I was sure there was a way around it; thanks a lot Dave !