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