Fred said:
Obviously, the lambda is using value at the end of the loop (4),
rather than what I want, value during the loop (0,1,2,3).
Christian said:
Right. I think the issue is that your lambda calls another funtion.
However, the function isn't called until the lambda is called later,
Hi everyone,
If I have this code:
def doLambda(val):
print value 2:, val
commands = []
for value in range(5):
print value 1:, value
commands.append(lambda:doLambda(value))
for c in commands:
c()
--
my output
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Fred Lionetti
Sent: Wednesday, November 16, 2005 2:32 PM
To: tutor@python.org
Subject: [Tutor] lambda in a loop
Hi everyone,
Hello,
If I have this code
def doLambda(val):
print value 2:, val
commands = []
for value in range(5):
print value 1:, value
commands.append(lambda:doLambda(value))
for c in commands:
c()
Hi Fred,
Ah, this one of those unfrequently asked questions.
lambdas in
def doLambda(val):
print value 2:, val
commands = []
for value in range(5):
print value 1:, value
commands.append(lambda:doLambda(value))
Close but not quite. Try:
commands.append(lambda v=value:doLambda(v))
value is a local variable in doLambda so
Christian Wyglendowski wrote:
-Original Message-
From: [EMAIL PROTECTED]
If I have this code:
snip
Obviously, the lambda is using value at the end of the loop (4),
rather than what I want, value during the loop (0,1,2,3).
Right. I think the issue is that your lambda calls another
The original solution does use a closure. The problem is that variables
are not bound into a closure until the scope of the variable exits. That
is why using a separate factory function works - the closure is bound
when the factory function exits which happens each time through the
loop. In
Just to be able to talk about things, let's give a name to the global
namespace as: G.
Whenever we call a function, we build a new environment that's chained up
to the one we're in at the time of function construction. This
corresponds to what people's ideas of the stack frame is.
Argh.