# How do I obtain the variables in a JuMP constraint?

**URL:** <https://discourse.julialang.org/t/how-do-i-obtain-the-variables-in-a-jump-constraint/107563>\
**Category:** Optimization (Mathematical)\
**Tags:** question, jump\
**Created:** [December 13, 2023, 11:11am UTC](https://discourse.julialang.org/t/how-do-i-obtain-the-variables-in-a-jump-constraint/107563 "2023-12-13T11:11:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![BdeKoning](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bdekoning/32/214557_2.png) [@BdeKoning](https://discourse.julialang.org/u/BdeKoning)\
**Post date:** [December 13, 2023, 11:11am UTC](https://discourse.julialang.org/t/how-do-i-obtain-the-variables-in-a-jump-constraint/107563/1 "2023-12-13T11:11:28Z")

</div>

Say I define a constraint with JuMP:

```julia
using JuMP
model = Model();
@variable(model, x[1:3]);
constraint = @constraint(model, c1, sum(x) <= 1)

```

How can I now, only using the variable `constraint`, obtain an iterable of variables present in this constraint?

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [December 13, 2023, 7:40pm UTC](https://discourse.julialang.org/t/how-do-i-obtain-the-variables-in-a-jump-constraint/107563/2 "2023-12-13T19:40:29Z")

</div>

Hi @BdeKoning, welcome to the forum,

There is no explicit function you can call, but if the constraint is linear (JuMP represents linear constraints as an affine function with type `AffExpr`), you can use:

```julia
julia> using JuMP

julia> model = Model();

julia> @variable(model, x[1:3]);

julia> constraint = @constraint(model, c1, sum(x) <= 1)
c1 : x[1] + x[2] + x[3] ≤ 1

julia> object = constraint_object(constraint)
ScalarConstraint{AffExpr, MathOptInterface.LessThan{Float64}}(x[1] + x[2] + x[3], MathOptInterface.LessThan{Float64}(1.0))

julia> object.func
x[1] + x[2] + x[3]

julia> typeof(object.func)
AffExpr (alias for GenericAffExpr{Float64, GenericVariableRef{Float64}})

julia> variables = [k for k in keys(object.func.terms)]
3-element Vector{VariableRef}:
 x[1]
 x[2]
 x[3]

```
