35

Assigning a variable directly does not modify expressions that used the variable retroactively.

>>> from sympy import Symbol
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> f = x + y
>>> x = 0

>>> f
x + y
Wesley
  • 1,412
  • 1
  • 15
  • 23
  • 1
    check out: http://docs.sympy.org/latest/tutorial/basic_operations.html for `expr.subs(x,val)` – Charlie Parker Aug 15 '17 at 20:36
  • The question in the title has no actual answer on this page, but it can be found [here](https://docs.sympy.org/latest/tutorials/intro-tutorial/basic_operations.html): *To perform multiple substitutions at once, pass a list of `(old, new)` pairs to `subs`*, example: `expr.subs([(x, 2), (y, 4), (z, 0)])` – mins Oct 28 '22 at 09:41

3 Answers3

53

To substitute several values:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30
Wesley
  • 1,412
  • 1
  • 15
  • 23
  • Was looking for an answer to this earlier. I understand why my code didn't work but I just needed a quick reference for the syntax to sub the values. Couldn't find anything within my first google search so I thought I would share the answer after I figured it out to hopefully save the next guy sometime. Posting Q&A style is a feature of stackoverflow. http://meta.stackoverflow.com/questions/290038/answer-your-own-question-qa-style – Wesley Oct 14 '15 at 05:47
  • what if f is a matrix of symbols? as in `a = symarray('a', 3)`? – Charlie Parker Aug 15 '17 at 20:23
  • What is happening when this does not work? Is there a difference between Symbol and sympy.var? – mathtick Aug 17 '20 at 09:30
6

The command x = Symbol('x') stores Sympy's Symbol('x') into Python's variable x. The Sympy expression f that you create afterwards does contain Symbol('x'), not the Python variable x.

When you reassign x = 0, the Python variable x is set to zero, and is no longer related to Symbol('x'). This has no effect on the Sympy expression, which still contains Symbol('x').

This is best explained in this page of the Sympy documentation: http://docs.sympy.org/latest/gotchas.html#variables

What you want to do is f.subs(x,0), as said in other answers.

Adrien
  • 469
  • 3
  • 11
2

Actually sympy is designed not to substitute values until you really want to substitute them with subs (see http://docs.sympy.org/latest/tutorial/basic_operations.html)

Try

f.subs({x:0})
f.subs(x, 0) # as alternative

instead of

x = 0
MSeifert
  • 145,886
  • 38
  • 333
  • 352