0

I tried to build a list of functions from a list of functions with list comprehension:

l  = [f1, f2]
l1 = [(lambda x: 2 * f(x)) for f in l]

But when I looked at the content of l1 it was completely different from what I expected:

>>> l = [lambda x: x, lambda x: -x]
>>> l1 = [lambda x: 2 * f(x) for f in l]
>>> [f(2) for f in l1]
[-4, -4]

while the outcome I expected was [4, -4].

I tried also with regular iterations (in place of list comprehension), and the result is the same puzzling:

>>> l1 = []
>>> for f in l:
>>>      print(f(2))
>>>      l1.append(lambda y: 2 * f(y))
>>>      print("0:",l1[0](2))
>>>      if len(l1) > 1:
>>>          print("1:",l[1](2))
4
0: 4
-4
0: -4
1: -4 

and the output I expected was different on the second to last line (0: 4 instead of 0: -4).

I'm really not understanding what's going on. Is someone able to explain this behavior? Is it intentional? (I really hope not, but I so confused that I don't know)

EDIT: the second snippet is changed according to the comment of @chepner

Annibale
  • 241
  • 3
  • 6
  • 1
    You may need lambda x, f=f: – quamrana Mar 12 '20 at 11:33
  • 1
    You aren't using `f` at all in the second definition of `l1`. – chepner Mar 12 '20 at 11:34
  • Thank you: @quamrana yours solution is working fine (that is the same of [one of the duplicated questions](https://stackoverflow.com/questions/19837486/python-lambda-in-a-loop)). – Annibale Mar 12 '20 at 11:51
  • And @chepner you are right, I copied the bugged version of my example. I am sorry to duplicated, I am often puzzled by closures and I forgot scopes for a while. – Annibale Mar 12 '20 at 11:52

0 Answers0