Gurobi linear expression object. A linear expression consists of a constant term, plus a list of coefficient-variable pairs that capture the linear terms. Linear expressions are used to build constraints. They are temporary objects that typically have short lifespans.
You generally build linear expressions using overloaded operators. For example, if x is a Var object, then x + 1 is a LinExpr object. Expressions can be built from constants (e.g., expr = 0), variables (e.g., expr = 1 * x + 2 * y), or from other expressions (e.g., expr2 = 2 * expr1 + x, or expr3 = expr1 + 2 * expr2). You can also modify existing expressions (e.g., expr += x, or expr2 -= expr1).
The full list of overloaded operators on LinExpr objects is as follows: +, +=, -, -=, *, *=, and /. In Python parlance, we've defined the following LinExpr functions: __add__, __radd__, __iadd__, __sub__, __rsub__, __isub__, __mul__, __rmul__, __imul__, and __div__.
We've also overloaded the comparison operators (==, <=, and >=), to make it easier to build constraints from linear expressions.
Note that it is much more efficient to build a large linear expression by extending an existing expression (using += or -=), rather than by repeatedly creating new expressions. The statement expr = expr + x creates a new copy of expr, for example, while expr += x just appends a new term. You can also use quicksum to build large expressions efficiently.
Another option for building expressions is to use the addTerms method, which adds an array of new terms at once. Terms can also be removed from an expression, using remove.
Individual terms in a linear expression can be queried using the getVar, getCoeff, and getConstant methods. You can query the number of terms in the expression using the size method.
Note that a linear expression may contain multiple terms that involve the same variable. These duplicate terms are merged when creating a constraint from an expression, but they may be visible when inspecting individual terms in the expression (e.g., when using getVar).