So I'm trying to make a list where a lambda functions are the elements of the list. The lambda function calls another function which I pass an argument to. The problem is that lambda function only 'saves' the last value for all other items in the list. See below
The question is what should I do to get the desired result?
Edit: The stated problem is simplified. I have to use lambda for the solution
This is the code I'm trying to understand the problem:
def f(B):
print(B)
A = [lambda: f(a) for a in ["foo", "faz", "baz"]]
for a in A:
a()
Desired result:
foo
faz
baz
Real result:
baz
baz
baz
CodePudding user response:
if you need to create an array of function calls you can achieve what you are trying to do with the following:
def f(x):
def g():
print(x)
return g
A = [f(a) for a in ["foo", "faz", "baz"]]
for a in A:
a()
output
foo
faz
baz
CodePudding user response:
While lambda
accesses the context it's defined in, a for
loop doesn#t create a new context each time it runs. That would be too inefficient.
Thus, by the time your code actually calls the lambda functions that context has ended and a
contains the last value the loop assigned to it.
Correct code:
def f(B):
print(B)
A = ["foo", "faz", "baz"]
for a in A:
f(a)
If this answer is not sufficient, please clarify why do you need that lambda in the first place.
CodePudding user response:
For loop in lambda saves last item of list so its better to write it way out lambda like this:
def b():
A = ["foo","faz","baz"]
For a in A:
Print(a)
and output is:
foo
faz
baz