Search code examples
pythonlistlambdadynamic-programming

Python lambda function in a list gives unexpected result


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

Solution

  • 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