'Generating constraints for optimization in scipy using loop

There are lots of constraints which I will use in optimization using scipy; so I need to generate the constraints by loop. Below there's a sample of my constraints:

cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 2},
        {'type': 'ineq', 'fun': lambda x: -x[1] - 2 * x[1] + 2},
        {'type': 'ineq', 'fun': lambda x: -x[2] - 2 * x[1] + 2})

There constraints are more than three... I use following loop to generate but I couldn't get the same output.

cons ={}
for i in range(50):
    cons['type'] = 'ineq'
    cons['fun'] = lambda x: -x[i] - 2 * x[1] + 2


Solution 1:[1]

You are updating cons everytime. Try this

_tmp = []
for i in range(50):
    _tmp.append({'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2})

cons = tuple(_tmp)

And this is more pythonic

cons = tuple([{'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2} for i in range(50)])

Solution 2:[2]

I don't think ozcanyarimdunya's answer would work because the i would be passed as reference instead of value into the constraint dictionary. In other words, in your constraint dictionary, i will always be 49.

The proper way should be:

_tmp = []
for i in range(50):
  _tmp.append({'type':'ineq', 'fun': lambda x, i = i: -x[i] - 2 * x[1] + 2})

cons = tuple(_tmp)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ozcanyarimdunya
Solution 2 Shuning Sun