5
$\begingroup$

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?

$\endgroup$
  • 9
    $\begingroup$ Variables command should work Variables[x^2 + y^3 + z] $\endgroup$ – Mad_Maximus Dec 18 '18 at 9:07
7
$\begingroup$

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.

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

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}
$\endgroup$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.