0

I have 2 functions: f, g:

f = lambda x:x**2
g = lambda x:x**3

I am trying to create new functions using the functions above, like this:

new_f, new_g = [lambda x:function(x)+30 for function in (f, g)]

When I run:

print(new_f(3))
print(new_g(3))

I expect:

39
57

but the actual output is:

57
57

With a little bit of debugging:

ids = [lambda: id(function) for function in (f, g)]

ids[0]() == ids[1]()

returns True.

But:

ids = [id(function) for function in (f, g)]

ids[0] == ids[1]

Returns False.

Why is lambda behaving this way?

user2390182
  • 67,685
  • 6
  • 55
  • 77
  • Does this answer your question? [How do I create a list of Python lambdas (in a list comprehension/for loop)?](https://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop) – user2390182 Oct 21 '21 at 16:03
  • Has little to do with `lambda`, but with scope, late binding and closures. See the dupe and [this common gotcha](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) – user2390182 Oct 21 '21 at 16:05
  • Yes, it does. Thanks for the help. Should I delete my question? – arcayi siken Oct 21 '21 at 17:53
  • Not necessary. It will eventually get closed as a duplicate and serve as a landing point to collect and redirect traffic. Nothing wrong with the question. – user2390182 Oct 21 '21 at 17:55

0 Answers0