The Wayback Machine - https://web.archive.org/web/20250117100720/https://www.geeksforgeeks.org/python-sympy-subs-method-2/
Open In App

Python | sympy.subs() method

Last Updated : 18 Jun, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.




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


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.




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


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.




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


Output:

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

Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg