Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
February 22nd, 2004, 06:40 AM
 George Sakkis
Registered User

Join Date: Feb 2004
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
Making closures in loop ?

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
February 22nd, 2004, 06:47 AM
 percivall
Contributing User

Join Date: Jul 2003
Posts: 133
Time spent in forums: < 1 sec
Reputation Power: 11
That is how it is bound.

Check what jeremy has got to say.

#3
February 22nd, 2004, 07:10 AM
 DevCoach
Contributing User

Join Date: Feb 2004
Location: London, England
Posts: 1,585
Time spent in forums: 2 Weeks 4 Days 2 h 58 m 23 sec
Reputation Power: 1372
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
February 22nd, 2004, 12:28 PM
 George Sakkis
Registered User

Join Date: Feb 2004
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
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 ?