# How to find all variables of an expression?

Is there a function that can extract a list of variables in an expression? For example, assume we have an expression

x^2+y^3+z


This expression has variables x, y and z. The result should be

{x, y, z}


. Is there a way to get this?

• Variables command should work Variables[x^2 + y^3 + z] – user59583 Dec 18 '18 at 9:07
• What about x[1]^2 + x[2]^3 + x[3]? Variables works, but none of the present answer do... – Michael E2 Aug 14 '19 at 13:48

For polynomial expressions @Buddha_the_Scientist's suggestion Variables will work. For more general expressions

expr = x^2 + y^3 + z
DeleteDuplicates@Cases[expr, _Symbol, ∞]


Should do the trick in most situations.

• Since all symbols are on level -1, you can use {-1} , instead of \[infinity]. – Fred Simons Dec 18 '18 at 11:14
• Might want to include only symbols in the "Global" context. I'd probably use Union instead of DeleteDuplicates to get them in canonical order. – Michael E2 Dec 18 '18 at 16:37

The undocumented IntegrategetAllVariables is a somewhat more robust version of Variables. It has a required second argument that specifies a variable to be excluded from the output. It just goes to show that internal functions are not always defined with the general user in mind.

IntegrategetAllVariables[x^2 + y^3 + z, {}] (* delete {} from output: *)
Variables[x^2 + y^3 + z]                     (*   {} can't happen anyway *)
(*
{x, y, z}
{x, y, z}
*)


A case Variables does not handle:

IntegrategetAllVariables[{x[0]'[t] + a t == 0,
y[1] == Sin[b[t]] x[0][t]^2}, {}]
Variables[{x[0]'[t] + a t == 0, y[1] == Sin@b[t] x[0][t]^2}]
(*
{a, t, b[t], y[1], x[0][t]}
{}
*)


Note how b[t] is treated differently than Sin[t], etc.:

IntegrategetAllVariables[a + b[t] - c[t + s] + x^y, {}]
IntegrategetAllVariables[a + Sin[t] - Cos[t + s] + x^y, {}]
(*
{a, x, y, b[t], c[s + t]}
{a, s, t, x, y}
*)


The second argument is useful in problems in which there is a principal independent variable and you want to get all the others. Excluding more than one, however, can only be achieved by hacking:

IntegrategetAllVariables[x^2 + y^3 + z, x]
(*  {y, z}  *)

xc /: {xc[a__]} := {a};  (* except the variables a.. *)
IntegrategetAllVariables[x^2 + y^3 + z, xc[x, y]]
(*  {z}  *)

• It is remarkable that IntegrategetAllVariables excludes symbols with NumericFunction attribute. – Shadowray Aug 14 '19 at 15:46

I like the following approach x):

expr = x^2 + y^3 + z;
Select[DeleteDuplicates@Level[expr, Depth@expr], Head[#] == Symbol &]


the result is:

{x, y, z}


Listing the expression might be an alternative for this simple example

List @@ (x^8 + y^3 + z) /. a_Symbol^n_ -> a

• How about 2 x^y - z`? – Shadowray Aug 14 '19 at 12:28
• Then i prefer Cases[List @@ (2 x^y - z), _Symbol, Infinity]//Union – user49047 Aug 14 '19 at 13:06
• List does not matter anymore Cases[(2 x^y - z), _Symbol, Infinity]//Union – user49047 Aug 14 '19 at 13:08