Search code examples
pythonsympysymbols

Extracting free symbols from a symbolic expression in sympy that was defined as a whole expression


Say I have two symbolic expressions:

a = symbols("a")
thing = symbols("2*a**2")

If one then calls a.free_symbols() one gets {a}, and for thing.free_symbols() one gets {2*a**2}.

Is there a way to format the object thing such that I get the equivalent expression but with eq_expr.free_symbols() = {a}?


Solution

  • First, note that writing brackets in a.free_symbols() gives an error: TypeError: 'set' object is not callable. free_symbols is a property of an expression, not a function.

    When you write thing = symbols("2*a**2") (docs), you create a new variable thing, whose name is "2*a**2" and which is not connected to a whatsoever.

    You can write thing = 2*a**2 (or thing = sympify("2*a**2") (docs)) to make thing an expression using variable a. In that case, thing.free_symbols would be {a}.