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

18,484

Solution 1

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])

Solution 2

A very useful attribute is atoms

x, y, z = sympy.symbols('x:z')
expr1 = sympy.exp(x + y) - sympy.sqrt(z)
display(expr1.free_symbols)
display(expr1.atoms(sympy.Symbol))

{𝑥,𝑦,𝑧} 
{𝑥,𝑦,𝑧}

In addition to symbols, atoms can extract other atoms, e.g.:

display(expr1.atoms(sympy.Function))
display(expr1.atoms(sympy.Number))
display(expr1.atoms(sympy.NumberSymbol))
display(expr1.atoms(sympy.function.AppliedUndef))
display(expr1.atoms(sympy.Mul))
display(expr1.atoms(sympy.Add))

(it's worth checking the output). Regarding the answer by gerrit

n = sympy.Symbol('n')
k2 = sympy.Sum(x, (n, 0, 10))
display(k2.free_symbols)
display(k2.variables)
display(k2.atoms(sympy.Symbol))

{𝑥} 
[𝑛]
{𝑛,𝑥}

Solution 3

Note that JuniorCompressors answer only lists free variables.

If you have a Sum, a Product, an Integral, or something similar, you may or may not want to additionally know the integration/summation variable using the .variables attribute:

In [216]: (x, n) = sympy.symbols("x n")

In [217]: f = sympy.Sum(x, (n, 0, 10))

In [218]: f.free_symbols
Out[218]: {x}

In [219]: f.variables
Out[219]: [n]
Share:
18,484

Related videos on Youtube

Michael A
Author by

Michael A

Account manager for a medical device company with a side interest in statistics and software development.

Updated on January 22, 2020

Comments

  • Michael A
    Michael A over 4 years

    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.

  • gerrit
    gerrit over 7 years
    Note that this only returns free symbols. For example, for Sum(T, (n, 1, N))/N it returns {N, T}, but not n.
  • MB-F
    MB-F about 7 years
    Note that the variablesattribute is only available for these concrete expression types. For example, this fails: f = sympy.Sum(x, (n, 0, 10)) * 2 because now f is of type Mul, which does not have the attribute.