title: Dynamically build a lambda function in python
body: <p>Supose that I want to generate a function to be later incorporated in a set of equations to be solved with scipy nsolve function. I want to create a function like this:</p>
  
  <p>xi + xi+1 + xi+3 = 1</p>
  
  <p>in which the number of variables will be dependent on the number of components. For example, if I have 2 components:</p>
  
  <pre><code> f = lambda x: x[0] + x[1] - 1
  </code></pre>
  
  <p>for 3:</p>
  
  <pre><code> f = lambda x: x[0] + x[1] + x[2] - 1
  </code></pre>
  
  <p>I specify the components as an array within the arguments of the function to be called:</p>
  
  <pre><code> def my_func(components):
          for component in components:
          .....
          .....
          return f
  </code></pre>
  
  <p>I can't just find a way of doing this. I've to be able to make it this way as this function and other functions need to be solved together with nsolve:</p>
  
  <pre><code> x0 = scipy.optimize.fsolve(f, [0, 0, 0, 0 ....])
  </code></pre>
  
  <p>Any help would be appreciated</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Since I'm not sure which is the best way of doing this I will fully explain what I'm trying to do:</p>
  
  <p>-I'm trying to generate this two functions to be later nsolved:</p>
  
  <p><img src="https://i.stack.imgur.com/NK2Xw.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/MDoBo.png" alt="enter image description here"></p>
  
  <p>So I want to create a function teste([list of components]) that can return me this two equations (Psat(T) is a function I can call depending on the component and P is a constant(value = 760)). </p>
  
  <p>Example:</p>
  
  <pre><code>  teste(['Benzene','Toluene'])
  </code></pre>
  
  <p>would return:</p>
  
  <p>xBenzene + xToluene = 1</p>
  
  <p>xBenzene<em>Psat('Benzene') + xToluene</em>Psat('Toluene') = 760</p>
  
  <p>in the case of calling: </p>
  
  <pre><code>   teste(['Benzene','Toluene','Cumene'])
  </code></pre>
  
  <p>it would return:</p>
  
  <p>xBenzene + xToluene + xCumene = 1</p>
  
  <p>xBenzene<em>Psat('Benzene') + xToluene</em>Psat('Toluene') + xCumene*Psat('Cumene') = 760</p>
  
  <p>All these x values are not something I can calculate and turn into a list I can sum. They are variables that are created as a function ofthe number of components I have in the system...</p>
  
  <p>Hope this helps to find the best way of doing this</p>