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)
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.
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.
Before Substitution : x**2 + 1 After Substitution : y**2 + 1
In this example we see that if the substituted value is numerical then sympy.subs() returns the solution of the resulting expression.
Before Substitution : cos(x) + 7 After Substitution : 8
In this example we see that we can do multiple substitutions if we pass a list of (old, new) pairs to subs.
Before Substitution : x**2 + 7*y + z After Substitution : 33
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.