problem with lambda / closures

Louis Steinberg lou at cs.rutgers.edu
Mon Nov 30 07:35:06 EST 2009


I have run into what seems to be a major bug, but given my short  
exposure to Python is probably just a feature:

running
Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

with file foo.py containing:

============================== clip here ============
def p(d):
     print d


l=[ ]
for k in [1,2,3]:
     l.append(lambda : p(k))

for f in l:
     f()

============================== clip here ============
I get output
3
3
3
instead of
1
2
3
which I would expect.  Can anyone explain this or give me a  
workaround?  Thank you






More information about the Python-list mailing list