Model.addConstrs()

addConstrs ( genexpr, name="" )

Add multiple constraints to a model using a Python generator expression. Returns a Gurobi tupledict that contains the newly created constraints, indexed by the values generated by the generator expression.

The first argument is a Python generator expression, a special feature of the Python language that allows you to iterate over a Python expression. For addConstrs, the expression should be a valid Gurobi constraint, and the result will be that a new constraint is added to the model for each iteration of the generator expression.

To give an example, if x is a Gurobi variable, then

  m.addConstr(x <= 1, name='c0')
would add a single linear constraint involving this variable. In contrast, if x is a list of Gurobi variables, then
  m.addConstrs((x[i] <= 1 for i in range(4)), name='c')
would add four constraints to the model. The entire first argument is a generator expression, where the indexing is controlled by the statement for i in range(4), The first constraint that results from this expression would be named c[0], and would involve variable x[0]. The second would be named c[1], and would involve variable x[1].

Generator expressions can be much more complex than this. They can involve multiple variables and conditional tests. For example, you could do:

  m.addConstrs((x[i,j] == 0 for i in range(4)
                            for j in range(4)
                            if i != j), name='c')

Note that if you supply a name argument, the generator expression must be enclosed in parenthesis. This requirement comes from the Python language interpreter.

Arguments:

genexpr: A generator expression, where each iteration produces a constraint.

name: Name pattern for new constraints. The given name will be subscripted by the index of the generator expression (so, for example, c would become c[0], c[1], etc.).

Return value:

A dictionary of Constr objects, indexed by the values specified by the generator expression.

Example usage:

  model.addConstrs(x.sum(i, '*') <= capacity[i] for i in range(5))
  model.addConstrs(x[i] + x[j] <= 1 for i in range(5) for j in range(5))

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.

Search