• Gurobi Staff

You can use the $$\texttt{if}$$-statement in other $$\texttt{for}$$-loops as well

import gurobipy as gpfrom gurobipy import GRBSetI=[i for i in range(3)]SetJ=[i for i in range(2)]m=gp.Model('example')x=m.addVars([(i,j) for i in SetI for j in SetJ if i!=j], vtype=GRB.BINARY, name='x')m.setObjective(sum(x[i,j] for i in SetI for j in SetJ if i!=j) , GRB.MINIMIZE)m.addConstrs((sum(x[i,j] for j in SetJ if i!=j)<=1 for i in SetI), name='constr1') m.optimize()

Alternatively, you could generate an index list for your variables. However, this will not make the construction of your constraints easier due to the need of individually accessing the first or second index.

import gurobipy as gpfrom gurobipy import GRBSetI=[i for i in range(3)]SetJ=[i for i in range(2)]varset = [(i,j) for i in SetI for j in SetJ if i!=j]m=gp.Model('example')x=m.addVars(varset, vtype=GRB.BINARY, name='x')m.setObjective(sum(x[i,j] for (i,j) in varset) , GRB.MINIMIZE)m.addConstrs((sum(x[i,j] for j in SetJ if i!=j)<=1 for i in SetI), name='constr1') m.optimize()

Best regards,
Jaromił

I also tried to work with var.index, but also got the same error message. Why is that?

import gurobipy as gpfrom gurobipy import GRBSetI=[i for i in range(3)]SetJ=[i for i in range(2)]m=gp.Model('example')x=m.addVars([(i,j) for i in SetI for j in SetJ if i!=j], vtype=GRB.BINARY, name='x')m.setObjective(sum(x[i,j] for i in SetI for j in SetJ if x[i,j].index!=-1 ) , GRB.MINIMIZE)m.addConstrs((sum(x[i,j] for j in SetJ if x[i,j].index!=-1)<=1 for i in SetI), name='constr1') m.optimize()
• Gurobi Staff

Working with var.index does not save you from trying to access key $$\texttt{(0,0)}$$. You are still accessing the not  available variable $$\texttt{x[0,0]}$$ to check its $$\texttt{.index}$$ field.

Best regards,
Jaromił