I just switched to Python from Matlab, and I want to use lambda function to map function f1(x,y)
with multiple arguments to one argument function f2(x)
for optimization.
I want that when I map the function f2(x) <- f1(x,y=y1)
then y
will stay constant no matter what y1
changes, in Matlab this is true by default but if I try in Python, it keeps changing as the following examples
>>> def f1(x,y):
>>> return (x+y)
>>> y1 = 2
>>> f2 = lambda x: f1(x,y1)
>>> f2(1)
3
I expect f2(1)
stays 3
even if I change y1
, however if I change y1
, the whole f1(1)
also changes as follows
>>> y1 = 5
>>> f2(1)
6
I wonder is there a way that when I declare f2 = lambda x: f1(x,y1)
then f1
will take the value of y1
at that time and fix it to f2
. The reason for this because I want to dynamically create different functions for different scenarios then sum them all.
I'm still new to Python, please help, much appreciate.
Try:
f2 = lambda x, y=y1: f1(x,y)
Your issue has to do with how closures work in Python
Your version of the lambda function will use the current version of y1
. You need to capture the value of y1
on the line where you've defined the lambda function. To do that, you can define it as the default value of a parameter (the y=y1
part).