# gurobipy.GurobiError: Second argument should be a list of Var

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
m.optimize()

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

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

main()


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?

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

## 1 Answer

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)