Nico Schlömer Nico Schlömer - 1 year ago 85
Python Question

SymPy: Swap two variables

In an expression like

import sympy

a = sympy.Symbol('a')
b = sympy.Symbol('b')

x = a + 2*b

I'd like to swap
to retrieve
b + 2*a
. I tried

y = x.subs([(a, b), (b, a)])
y = x.subs({a: b, b: a})

but neither works; the result is
in both cases as
, for some reason, gets replaced first.

Any hints?

Answer Source

There is a simultaneous argument you can pass to the substitution, which will ensure the substitutions happen simultaneously and don't interfere with one another as they are doing now.

y = x.subs({a:b, b:a}, simultaneous=True)


2*a + b

From the docs for subs:

If the keyword simultaneous is True, the subexpressions will not be evaluated until all the substitutions have been made.