Giovanni Bajo wrote: > Yes but: > >>>> a = [] >>>> for i in range(10): > ... a.append(lambda: i) > ... >>>> print [x() for x in a] > [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > > This subtle semantic of lambda is quite confusing, and still forces people to > use the "i=i" trick. If you'd like each function instance to have a separate closure scope, then *give* each function a separate closure scope, instead of making them all share the same one the way you have above: >>> def make_f(i): ... def f(): ... return i ... return f ... >>> a = [] >>> for i in range(10): ... a.append(make_f(i)) ... >>> print [x() for x in a] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- http://www.boredomandlaziness.org
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4