# How do I get a list of all the variable present in an algebraic expression? [duplicate]

I have an algebraic expression

(l[d,1]/(-l[d,1]+m[dd,1] p[dd]+m[du,1] p[du])+l[d,2]/(-l[d,2]+m[dd,2] p[dd]+m[ud,2] p[ud])+l[u,1]/(-l[u,1]+m[uu,1] p[uu])+l[u,2]/(-l[u,2]+m[uu,2] p[uu]))/(l[d,1]+l[d,2]+l[u,1]+l[u,2])


and I want to get a list of all the variables that are present in it excluding the mathematical operators , e.g., {l[d,1], m[dd,1], p[dd], ...}. That is, replace all the heads that are Plus, Power or Times by the head List, Flatten the resulting list and remove the duplicates. How do I do that?

## marked as duplicate by Kuba♦, Community♦Apr 10 '15 at 10:33

• Short answer，Ma thematic does not have such a function. Unlike Maple, you can use 'indets'. But sometimes, you can try Variables[] with Level[] to get an answer in Mathematica. I have asked the same thing before, and there is no unified answer that can give you a satisfied answer if you are only looking for "variables", not in Mathematica. – Chen Stats Yu Apr 10 '15 at 8:17
• – Chen Stats Yu Apr 10 '15 at 8:24

f = (l[d, 1]/(-l[d, 1] + m[dd, 1] p[dd] + m[du, 1] p[du]) + l[d, 2]/(-l[d, 2] + m[dd, 2] p[dd] + m[ud, 2] p[ud]) + l[u, 1]/(-l[u, 1] + m[uu, 1] p[uu]) + l[u, 2]/(-l[u, 2] + m[uu, 2] p[uu]))/(l[d, 1] + l[d, 2] + l[u, 1] + l[u, 2])

vars = Variables[f]


Output

{l[d, 1], l[d, 2], l[u, 1], l[u, 2], m[dd, 1], p[dd], m[du, 1], p[du],  m[dd, 2], m[ud, 2], p[ud], m[uu, 1], p[uu], m[uu, 2]}


Honestly speaking, I have seen before a similar answer using the Variable here, but can't find it. If someone find it please post it on comment. I would be glad to add the reference.

• Thanks ! Variables was the function I was looking for. – Pisto Apr 10 '15 at 10:38
expr=(l[d, 1]/(-l[d, 1] + m[dd, 1] p[dd] + m[du, 1] p[du]) + l[d, 2]/(-l[d, 2] + m[dd, 2] p[dd] + m[ud, 2] p[ud]) + l[u, 1]/(-l[u, 1] + m[uu, 1] p[uu]) + l[u, 2]/(-l[u, 2] + m[uu, 2] p[uu]))/(l[d, 1] + l[d, 2] + l[u, 1] + l[u, 2])

Variables[Level[expr, 2]]


Again, there is no such single function in Mathematica, but you can try combinations of functions like 'Variables' and 'Level'. If you have Maple, indets is the one you are looking for.

varslist = Select[Intersection@

where orig is your original expression.