# [SOLVED] Creating multiple functions using a for loop

## Issue

I am trying to create multiple constraint functions to feed scipy.minimize.

The minimize function is:

``````res1 = minimize(f, x0, args, method='SLSQP', bounds=bnds, constraints=cons, options={'disp': True})
``````

I have set cons to:

``````cons = [con1, con2, con3, con4]
con1 = {'type': 'eq', 'fun': constraint1}
con2 = {'type': 'eq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3}
con4 = {'type': 'eq', 'fun': constraint4}

def constraint1(x):
return x + x + x + x + x + x + x + x + x - 4321
def constraint2(x):
return x + x + x + x + x + x + x + x + x - 123
def constraint3(x):
return x + x + x + x + x + x + x + x + x - 1234
def constraint4(x):
return x + x + x + x + x + x + x + x + x - 432
``````

How can I automate this process by using a for loop? The problem is to create function with parametric name

## Solution

You needn’t give the functions names at all:

``````def make_constraint(i,j,c):
def constraint(x):
return sum(x[i:j])+c

cons=[dict(type='eq',fun=make_constraint(i*9,(i+1)*9,c))
for i,c in enumerate([-4321,-123,-1234,-432])]
``````

This sort of approach will not in general run quite as fast as the hand-written functions, since values like `i` and `j` must be retrieved on every call; if that matters, it is possible to use the `ast` module to actually create new Python functions without `exec` (and its associated lack of structure and security).