How can I get a list of the symbols in a sympy expression?

Michael A picture Michael A · May 3, 2015 · Viewed 12.3k times · Source

For example, if I run

import sympy
x, y, z = sympy.symbols('x:z')
f = sympy.exp(x + y) - sympy.sqrt(z)

is there any method of f that I can use to get a list or tuple of sympy.Symbol objects that the expression contains? I'd rather not have to parse srepr(f) or parse downward through f.args.

In this case, g.args[0].args[1].args[0] gives me Symbol("z"), while g.args[1].args[0].args gives me the tuple (Symbol("x"), Symbol("y")), but obviously these are expression-specific.

Answer

JuniorCompressor picture JuniorCompressor · May 3, 2015

You can use:

f.free_symbols

which will return a set of all free symbols.

Example:

>>> import sympy
>>> x, y, z = sympy.symbols('x:z')
>>> f = sympy.exp(x + y) - sympy.sqrt(z)
>>> f.free_symbols
set([x, z, y])