
July 1, 2006
1:15 p.m.
Giovanni Bajo wrote:
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.
This has *nothing* to do with the semantics of lambda! It's because Python's for-loop doesn't put its control variable in a new scope, the way Scheme's equivalent construct does. *That's* what needs to be addressed to fix this problem. I've made a suggestion about that before, but Guido rejected it, so I won't repeat it here. -- Greg