lambda function of another function but force fixed argument
<p>I just switched to Python from Matlab, and I want to use lambda function to map function <code>f1(x,y)</code> with multiple arguments to one argument function <code>f2(x)</code> for optimization. 
I want that when I map the function <code>f2(x) &lt;- f1(x,y=y1)</code> then <code>y</code> will stay constant no matter what <code>y1</code> changes, in Matlab this is true by default but if I try in Python, it keeps changing as the following examples</p>

<pre><code>&gt;&gt;&gt; def f1(x,y):
&gt;&gt;&gt;    return (x+y)
&gt;&gt;&gt; y1 = 2
&gt;&gt;&gt; f2 = lambda x: f1(x,y1)
&gt;&gt;&gt; f2(1)
3
</code></pre>

<p>I expect <code>f2(1)</code> stays <code>3</code> even if I change <code>y1</code>, however if I change <code>y1</code>, the whole <code>f1(1)</code> also changes as follows</p>

<pre><code>&gt;&gt;&gt; y1 = 5
&gt;&gt;&gt; f2(1)
6
</code></pre>

<p>I wonder is there a way that when I declare <code>f2 = lambda x: f1(x,y1)</code> then <code>f1</code> will take the value of <code>y1</code> at that time and fix it to <code>f2</code>. 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.</p>

<p>Try:</p>

<pre><code>f2 = lambda x, y=y1: f1(x,y)
</code></pre>

<p>Your issue has to do with <a href="http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures" rel="nofollow">how closures work in Python</a></p>

<p>Your version of the lambda function will use the current version of <code>y1</code>.  You need to <em>capture</em> the value of <code>y1</code> 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 <code>y=y1</code> part).</p>

python function lambda