problem with lambda / closures

L

Louis Steinberg

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
 
M

Marco Mariani

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


Yes, it works as advertised :-/

which I would expect. Can anyone explain this or give me a workaround?

like this?

def p(d):
print d


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

for f in l:
f()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top