How does variable capture work with lambdas and functions in python?

35 Views Asked by At

I am very confused by this code:

def run_test():
    lambda_list = []
    for x in ["a", "b", "c"]:
        def print_x():
            print(x)

        lambda_list += [(print_x,)]


    for (l,) in lambda_list:
        l()

run_test()
        

Which when I run produces:

c
c
c

I natively would expect that it would produce

a
b
c

Is there a way to have the variable be captured and not reset in each iteration?

Thanks, /YGA

0

There are 0 best solutions below