To substitute several values:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30
Answer from Wesley on Stack Overflow
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί tutorials β€Ί intro-tutorial β€Ί basic_operations.html
Basic Operations - SymPy 1.14.0 documentation
>>> from sympy import * >>> x, y, z = symbols("x y z") One of the most common things you might want to do with a mathematical expression is substitution. Substitution replaces all instances of something in an expression with something else. It is done using the subs() method.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί python-sympy-subs-method-2
Python sympy.subs() method - GeeksforGeeks
July 12, 2025 - Explanation: The code defines the symbolic variables x, y, and z using SymPy. It then creates an expression x**2 + 7 * y + z, and substitutes values for x, y, and z using the subs() method.
Discussions

subs is slow
Hi, it seems that the .subs function is quite slow. When I have a long expression e (can contain nonlinear terms like x**2, y*x*z), calling e.subs(some_dict) takes some noticeable time (two sec'... More on github.com
🌐 github.com
5
October 9, 2021
python - How can I substitute multiple symbols in an expression in SymPy? - Stack Overflow
I understand why my code didn't ... 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. meta.stackoverflow.com/questions/290038/… 2015-10-14T05:47:37.967Z+00:00 ... What is happening when this does not work? Is there a difference between Symbol and sympy.v... More on stackoverflow.com
🌐 stackoverflow.com
python - In sympy, evaluating an expression using .subs() when that expression has been defined in another function - Stack Overflow
If I define a symbolic expression inside a function, how do I evaluate that expression using .subs() outside that function. The following code demonstrates the issue: import sympy as sp def myFun(): x = sp.symbols("x", positive = True) y = 3*x return y expr = myFun() print(expr.subs({x:10})) More on stackoverflow.com
🌐 stackoverflow.com
Sympy problem with subs
i don't get the same result as you -- it works for me. In [9]: r, N, B = symbols('r,N,B') In [10]: J11 = diff(r*N*(1-N/B), N) In [11]: J11 Out[11]: βŽ› N⎞ Nβ‹…r rβ‹…βŽœ1 - β”€βŽŸ - ─── ⎝ B⎠ B In [12]: J11.subs(r, 4) Out[12]: 8β‹…N 4 - ─── B More on reddit.com
🌐 r/Python
3
2
December 8, 2011
🌐
TutorialsPoint
tutorialspoint.com β€Ί home β€Ί sympy β€Ί sympy substitution
SymPy Substitution
March 5, 2015 - One of the most basic operations to be performed on a mathematical expression is substitution. The subs() function in SymPy replaces all occurrences of first parameter with second.
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί modules β€Ί numeric-computation.html
Numeric Computation - SymPy 1.14.0 documentation
It runs at SymPy speeds. The .subs(...).evalf() method can substitute a numeric value for a symbolic one and then evaluate the result within SymPy.
🌐
GitHub
github.com β€Ί sympy β€Ί sympy β€Ί issues β€Ί 22240
subs is slow Β· Issue #22240 Β· sympy/sympy
October 9, 2021 - Hi, it seems that the .subs function is quite slow. When I have a long expression e (can contain nonlinear terms like x**2, y*x*z), calling e.subs(some_dict) takes some noticeable time (two sec's or so). In fact subs is often slower than solving large equations.
Author Β  nguyenthanhvuh
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί modules β€Ί core.html
Core - SymPy 1.14.0 documentation
An atom is an expression with no subexpressions. ... The registry for the singleton classes (accessible as S). ... This class serves as two separate things. The first thing it is is the SingletonRegistry. Several classes in SymPy appear so often that they are singletonized, that is, using some metaprogramming they are made so that they can only be instantiated once (see the sympy.core.singleton.Singleton class for details).
Find elsewhere
🌐
Problem Solving with Python
problemsolvingwithpython.com β€Ί 10-Symbolic-Math β€Ί 10.04-Expressions-and-Substitutions
Expressions and Substitutions - Problem Solving with Python
Use SymPy's .subs() method to insert a numerical value into a symbolic math expression. The first argument of the .subs() method is the mathematical symbol and the second argument is the numerical value.
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί explanation β€Ί gotchas.html
Gotchas and Pitfalls - SymPy 1.14.0 documentation
The subs() function does not modify the original expression expr. Rather, a modified copy of the expression is returned. This returned object is stored in the variable expr_modified. Note that unlike C/C++ and other high-level languages, Python does not require you to declare a variable before it is used. SymPy uses the same default operators as Python.
Top answer
1 of 3
1

@cards answer is not going to work, the reason is that you have defined x to be positive, instead when calling print(expr.subs({'x':10})) the string 'x' will generate a generic symbol, without assumptions.

You either create your symbols outside of the function, like this:

import sympy as sp

x = sp.symbols("x", positive = True)
def myFun():
    y = 3*x
    return y

expr = myFun()
print(expr.subs({x:10}))
# out: 30

Or you can retrieve the symbols that make up a symbolic expression with the free_symbol attribute, like this:

import sympy as sp

def myFun():
    x = sp.symbols("x", positive = True)
    y = 3*x
    return y

expr = myFun()
x = expr.free_symbols.pop()
print(expr.subs({x:10}))
# out: 30

EDIT (to accommodate comment):

I was just wondering but what if the expression had three variables, say 5*y + 3*x + 7*z? I tried the code you provided. The line expr.free_symbols.pop() only gives one of the variables - it gives x. Is there a way to use free_symbols to get all three variables?

free_symbols returns a set with all variables. If the expression is expr = 5*y + 3*x + 7*z, then expr.free_symbols returns {x, y, z}.

pop() is a method of Python's set: it returns the first element of a set.

To get all the variables of your expression you could try: x, y, z = expr.free_symbols, or x, y, z = list(expr.free_symbols). However, this creates the following problem: execute print(x, y, z) and you'll get something similar to: y z x. In other words, the symbols returned by expr.free_symbols are unordered. This is the default Python behavior.

Can we get ordered symbols? Yes, we can sort them alphabetically with : x, y, z = sorted(expr.free_symbols, key=str). If we now execute print(x, y, z) we will get x y z.

2 of 3
0

Let's create an expression with two symbols in it:

In [44]: x, y = symbols('x, y')

In [45]: expr = sin(y) + x**2

Suppose that we only have the expression as a local variable. We can find the symbols it contains using free_symbols. We can use that to build a dict that maps symbol names (as strings) to the symbols themselves:

In [46]: expr.free_symbols
Out[46]: {x, y}

In [47]: syms = {s.name: s for s in expr.free_symbols}

In [48]: syms
Out[48]: {'y': y, 'x': x}

This mapping is important because different symbols with the same names but different assumptions are not interchangeable. With that we can substitute the symbol whose name is 'x' like this:

In [49]: expr.subs(syms['x'], 2)
Out[49]: sin(y) + 4
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί explanation β€Ί best-practices.html
Best Practices - SymPy 1.14.0 documentation
This is because the result is represented symbolically, meaning, for instance, one can later substitute specific values for the symbols and it will evaluate to the specific case, even if it is combined with other expressions. ... >>> from sympy import Piecewise, pprint >>> expr = Piecewise((1, x > 0), (0, True)) >>> pprint(expr, use_unicode=True) ⎧1 for x > 0 ⎨ ⎩0 otherwise >>> expr.subs(x, 1) 1 >>> expr.subs(x, -1) 0
🌐
Reddit
reddit.com β€Ί r/python β€Ί sympy problem with subs
r/Python on Reddit: Sympy problem with subs
December 8, 2011 -

I'm trying to streamline a program to solve elements of a Jacobian matrix. Sympy is working for the most part, but there seems to be one bug.

J11 = diff(rN(1-N/B),N)

J11 r*(1 - N/B) - N*r/B

When I try to enter the variable name, it doesn't substitute the variable that I want.

( J11).subs(r,4) r*(1 - N/B) - N*r/B

However, the equation itself gives me the result I want.

(r*(1 - N/B) - Nr/B).subs(r,4) 4 - 8N/B

Any way to get this to work with the variable name?

🌐
Byu
labs.acme.byu.edu β€Ί PythonEssentials β€Ί SympyIntro β€Ί SympyIntro.html
Intro to SymPy β€” ACME Labs
Every SymPy expression has a subs() method that substitutes one variable for another. The result is usually still a symbolic expression, even if a numerical value is used in the substitution. The evalf() method actually evaluates the expression numerically after all symbolic variables have ...
🌐
Brown University
cfm.brown.edu β€Ί people β€Ί dobrush β€Ί am33 β€Ί SymPy β€Ί index.html
SymPy TUTORIAL for Applied Differential Equations I
SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf. Let’s compute the first 100 digits of \(\pi\). >>> pi.evalf(100) 3.1415926535897932384626433832795028841971693993751058...
🌐
Julia Programming Language
discourse.julialang.org β€Ί new to julia
How to use sympy to replace a symbol in a derivative? - New to Julia - Julia Programming Language
January 4, 2023 - Hello, good afternoon. Im trying to use sympy to calc an gradient descent in some symbols and having troubles with index. This algorithm is pretty simple using to calc derivative by hand. Using sympy things gets wierd. m, b, i, n = symbols("m b i n"); x, y = symbols("x y", cls=sympy.Function); sumofsquares = sympy.Sum((m * x(i) + b - y(i))^2, (i, 0, n)); print("sum of squares:"); display(sumofsquares); # derivative of m dm = sympy.diff(sumofsquares, m); # derivatime of b db = sympy.diff(sum...
🌐
SymPy
docs.sympy.org β€Ί latest β€Ί tutorials β€Ί intro-tutorial β€Ί gotchas.html
Gotchas - SymPy 1.14.0 documentation
>>> x = symbols('x') >>> expr = x + 1 >>> expr.subs(x, 2) 3 Β· Another very important consequence of the fact that SymPy does not extend Python syntax is that = does not represent equality in SymPy. Rather it is Python variable assignment.
🌐
Google Groups
groups.google.com β€Ί g β€Ί sympy β€Ί c β€Ί b_Yv6s15Y0Q
Difference between replace and subs?
December 4, 2012 - (BTW as an aside, in some places ... properly formatted -- just thought I'd mention.) ... The subs method is able to call helper methods that request help in identifying how an expression might be replaced in an expression; I think replace (and definitely xreplace) are more literal ...
🌐
ProjectPro
projectpro.io β€Ί recipes β€Ί what-is-substitution-operation-sympy
What is substitution operation in Sympy -
August 5, 2022 - The subs() function in SymPy replaces all occurrences of the first parameter with the second.