The post “How can I convert a list of strings into sympy variables?” discusses how to generate SymPy symbols from a list of strings. My question is what steps are needed to use these symbols x, y and z in SymPy calculations?
I tried something along the lines
JavaScript
x
11
11
1
from sympy import symbols, solveset
2
3
var_as_strings = ['x', 'y', 'z']
4
var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
5
var_as_symbol_objects
6
7
for x1, x2 in zip(var_as_symbol_objects, var_as_strings):
8
x1 = symbols(x2)
9
10
soln = solveset(x-y-z, x)
11
but I get the error “NameError: name ‘x’ is not defined”. Any help is greatly appreciated.
Advertisement
Answer
You can create Python variables in the current namespace from a list of strings (or a string of space or comma separated names) with var
:
JavaScript
1
8
1
>>> names = 'x y z' # or 'x, y, z'
2
>>> var(names)
3
(x, y, z)
4
>>> var(list('xyz'))
5
[x, y, z]
6
>>> var(set('xyz'))
7
{x, y, z}
8
In all cases, after issuing the var
command you will be able to use variables that have been assigned SymPy symbols with the same name.