Link Search Menu Expand Document (external link)

How to substitute a value for a symbolic variable (in Python, using SymPy)

See all solutions.

Task

If we’ve defined a symbolic variable and used it in a formula, how can we substitute a value in for it, to evaluate the formula? This is often informally called “plugging in” a value.

Related tasks:

Solution

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output

Let’s assume we’ve defined a variable and created a formula, as covered in how to create symbolic variables.

1
2
3
var( 'x' )
formula = x**2 + x
formula

$\displaystyle x^{2} + x$

We can substitute a value for $x$ using the subs function. You provide the variable and the value to substitute.

1
formula.subs( x, 8 )  # computes 8**2 + 8

$\displaystyle 72$

If you had to substitute values for multiple variables, you can use multiple subs calls or you can pass a dictionary to subs.

1
2
3
var( 'y' )
formula = x/2 + y/3
formula

$\displaystyle \frac{x}{2} + \frac{y}{3}$

1
formula.subs( x, 10 ).subs( y, 6 )

$\displaystyle 7$

1
formula.subs( { x: 10, y: 6 } )

$\displaystyle 7$

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)