Substitutions
Let us first consider a simple symbolic expression:
x, a = symbols('x a') b = x + a
What happens if we set x = 0
? We observe that b
did not change. What we did was that we changed the Python variable x
. It now no longer refers to the symbol object but to the integer object 0. The symbol represented by the string 'x'
remains unaltered, and so does b
.
Instead, altering an expression by replacing symbols by numbers, other symbols, or expressions is done by a special substitution method which can be seen in following code:
x, a = symbols('x a') b = x + a c = b.subs(x,0) d = c.subs(a,2*a) print(c, d) # returns (a, 2a)
This method takes one or two arguments:
b.subs(x,0) b.subs({x:0}) # a dictionary as argument
Dictionaries as arguments allow us to make several substitutions in one step:
b.subs({x:0, a:2*a}) # several substitutions in one
As items in dictionaries have no defined order - one never knows...