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>As already pointed out, your issue comes down to how closures work. However, you really shouldn't be using a lambda for this - lambdas are for anonymous functions. Make a higher-order function with <code>def</code> statements instead:</p>

<pre><code>&gt;&gt;&gt; def f1(x,y):
...   return x + y
... 
&gt;&gt;&gt; def f1_factory(y):
...   def f1_y(x):
...     return f1(x,y)
...   return f1_y
... 
&gt;&gt;&gt; f1_factory(6)(4)
10
&gt;&gt;&gt; f1_factory(5)(4)
9
</code></pre>

<p>It also avoids the problem you encountered:</p>

<pre><code>&gt;&gt;&gt; y = 3
&gt;&gt;&gt; newfunc = f1_factory(y)
&gt;&gt;&gt; newfunc(1)
4
&gt;&gt;&gt; y = 20
&gt;&gt;&gt; newfunc(1)
4
&gt;&gt;&gt; 
</code></pre>

<p>From <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations" rel="nofollow">PEP8</a>:</p>

<blockquote>
  <p>Always use a def statement instead of an assignment statement that
  binds a lambda expression directly to an identifier.</p>
  
  <p>Yes:</p>
  
  <p>def f(x): return 2*x </p>
  
  <p>No:</p>
  
  <p>f = lambda x: 2*x </p>
  
  <p>The first form means that the name of the resulting
  function object is specifically 'f' instead of the generic <code>&lt;lambda&gt;</code>.
  This is more useful for tracebacks and string representations in
  general. The use of the assignment statement eliminates the sole
  benefit a lambda expression can offer over an explicit def statement
  (i.e. that it can be embedded inside a larger expression)</p>
</blockquote>

python function lambda