0

I'm trying to add constraints to a mathematical model iteratively with Scipy using lambda function as below:

cons = []

for i in range(3):
    a = lambda x: np.array([x[i] - 600])
    cons.append({'type': 'ineq', 'fun': a})

But it executes only the last call, when i=2. How can I do to make this a full evaluation and execute all the elements in iteration? I read a couple of posts here without sucesss

Fann Wong
  • 21
  • 2
  • Does this answer your question? [What do (lambda) function closures capture?](https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture) – Silvio Mayolo Sep 22 '20 at 02:40
  • Check the linked question. In particular, Adrien's answer (involving the default argument capture trick) is likely to fix your exact problem. – Silvio Mayolo Sep 22 '20 at 02:41
  • Another answer that discusses this issue: https://stackoverflow.com/a/34021333/901925 – hpaulj Sep 22 '20 at 02:41
  • yes I checked all those. I don't understand why this constraint = (lambda x: x[0] - 600, lambda x: x[1] - 600, lambda x: x[2] - 600, lambda x: x[3] - 600) works and this for i in range(3): constraint.append(lambda x: x[i] - 600) constraint = tuple(constraint) doesn't – Fann Wong Sep 22 '20 at 15:38

0 Answers0