The following error was encountered when using LinExpr in gurobi:

    contribution = LinExpr(coefficients, variables)
  File "src\gurobipy\linexpr.pxi", line 83, in gurobipy.LinExpr.__init__
gurobipy.GurobiError: Second argument should be a list of Var

And my code as follow:

from gurobipy import *

def process_group(item_values: list, m: Model, prefix: str):
    # Create one binary variable per item in the group.
    model = Model()
    shape = len(item_values)
    bns = model.addVars(shape, vtype=GRB.BINARY, name=(prefix + "_choice"))

    # A constraint that ensures only 1 item in this set is chosen.
    model.addConstr(bns.sum() == 1, name=(prefix + "_choose1"))

    # contribution = x11 * b11 + x12 * b12 + ...
    coefficients = item_values
    variables = tuplelist(bns)
    print("coefficients:", coefficients)
    print("variables:", variables)
    contribution = LinExpr(coefficients, variables)
    return contribution

def main():
    # Data and parameters
    group_values_list = [[10, 20, 30], [20, 30], [10],
                         [10, 30], [10, 20, 30, 40],
                         [10, 20, 30]]
    max_total_value = 100
    for i, g in enumerate(group_values_list):
        print("i:", i)
        print("g:", g)

    # Model
    m = Model()
    contributions = [process_group(g, m, "set%d" % i)
                     for i, g in enumerate(group_values_list)]
    total_value = sum(contributions)

    # Limit the total value of the chosen items
    m.addConstr(total_value <= max_total_value,
                "total value limit")

    # Objective is to maximize the total value
    m.setObjective(total_value, GRB.MAXIMIZE)

    # Optimize model

    for v in m.getVars():
        print('%s %g' % (v.varName, v.x))

    print('Obj: %g' % m.objVal)


The purpose of the code is to find out all the solutions which the elements of the solution must belong to the corresponding list. How should I fix this error?

  • $\begingroup$ If Richard's answer resolved your problem, please make sure to accept it. $\endgroup$
    – EhsanK
    Jul 18, 2021 at 21:35

1 Answer 1


The problem is that you create a tuplelist of a list. The function addVars returns a list of variables objects already. This means, you should be able to simply do:

contribution = LinExpr(coefficients, bns)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.