0

I wrote this simple Python code

PP = [[0, 1], [1, 0]]
F0 = lambda x,y: x
FF = [
    lambda u: F0(*(u[i] for i in p)) for p in PP
]
print(FF[0]([1, 2]))
print(FF[1]([1, 2]))

And I got

2
2

While I expected

1
2

With some other tests with more permutations I could observe that FF is indeed a list of the right length but contains only copies of the last function we want. Someone could explain me why ??

Nanored
  • 31
  • 7
  • You are creating a list of 2 identical functions, both of which have the *name* `p`, not a value *of* `p`, in their definition. – chepner Jul 27 '22 at 17:49
  • Thx, I see the problem. Very strange language.. Do you know how can I use the value of `p` instead of the name ? – Nanored Jul 27 '22 at 17:58
  • Ok, I got it, I can add the argument p=p to put the value of p in the closure of the lambda – Nanored Jul 27 '22 at 18:03
  • It's not that strange: the body of a lambda expression isn't evaluated any more than the body of a `def` statement is. – chepner Jul 27 '22 at 18:22

0 Answers0