Python | sympy.subs() method

With the help of sympy.subs() method, we can substitute all instances of a variable or expression in a mathematical expression with some other variable or expression or value.

Syntax: math_expression.subs(variable, substitute)

Parameters:
variable – It is the variable or expression which will be substituted.
substitute – It is the variable or expression or value which comes as substitute.

Returns: Returns the expression after the substitution.

Example #1:

In this example we can see that by using sympy.subs() method, we can find the resulting expression after substituting a variable or expression with some other variable or expression or value. Here we use symbols() method also to declare a variable as symbol.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import sympy
from sympy import *
  
x, y = symbols('x y')
exp = x**2 + 1
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs(x, y) 
    
print("After Substitution : {}".format(res_exp)) 

chevron_right


Output:

 
Before Substitution : x**2 + 1
After Substitution : y**2 + 1

 
Example #2:

In this example we see that if the substituted value is numerical then sympy.subs() returns the solution of the resulting expression.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import sympy
from sympy import * 
  
x = symbols('x')
exp = cos(x) + 7
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs(x, 0
    
print("After Substitution : {}".format(res_exp)) 

chevron_right


Output:

 
Before Substitution : cos(x) + 7
After Substitution : 8

Example #3:

In this example we see that we can do multiple substitutions if we pass a list of (old, new) pairs to subs.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import sympy
from sympy import * 
  
x, y, z = symbols('x y z')
exp = x**2 + 7 * y + z
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs([(x, 2), (y, 4), (z, 1)]) 
    
print("After Substitution : {}".format(res_exp)) 

chevron_right


Output:

 
Before Substitution : x**2 + 7*y + z
After Substitution : 33


My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.