|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
Hi there,
I want to create a list of functions with something like: closures = [lambda x: i*x for i in range(10)] so that closures[0] = 0*x closures[1] = 1*x closures[2] = 2*x ... closures[9] = 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 ? George |
|
#2
|
|||
|
|||
|
|
|
#3
|
|||
|
|||
|
You can get it to work the way you want by passing in i as a default parameter, i.e.:
Code:
>>> closures = [lambda x, i=i: i*x for i in range(10)] >>> closures[1](2) 2 >>> closures[4](2) 8 This was the standard way to simulate closures in Python prior to 2.1, when it did not have the new scoping rules. Dave - The Developers' Coach |
|
#4
|
|||
|
|||
|
I was sure there was a way around it; thanks a lot Dave !
George |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Making closures in loop ? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|