Nico Schlömer - 10 months ago 65

Python Question

In an expression like

`import sympy`

a = sympy.Symbol('a')

b = sympy.Symbol('b')

x = a + 2*b

I'd like to swap

`a`

`b`

`b + 2*a`

`y = x.subs([(a, b), (b, a)])`

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

but neither works; the result is

`3*a`

`b`

Any hints?

Answer

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

**Outputs**:

```
2*a + b
```

If the keyword

`simultaneous`

is`True`

, the subexpressions will not be evaluated until all the substitutions have been made.