0

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
eiskaffe
  • 11
  • 3
  • 3
    Does this answer your question? [Lambda function in list comprehensions](https://stackoverflow.com/questions/6076270/lambda-function-in-list-comprehensions) – Igor Moraru Dec 09 '22 at 17:28
  • 1
    `a` is a free variable in the lambda expression; you are defining the same function 3 times. It's not the *value* of `a` that's used to define the function. – chepner Dec 09 '22 at 17:37

3 Answers3

0

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
Chris
  • 26,361
  • 5
  • 21
  • 42
0

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.

Matthias Urlichs
  • 2,301
  • 19
  • 29
0

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
SR3142
  • 550
  • 3
  • 9