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
from sympy import symbols, solveset
var_as_strings = ['x', 'y', 'z']
var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
var_as_symbol_objects
for x1, x2 in zip(var_as_symbol_objects, var_as_strings):
x1 = symbols(x2)
soln = solveset(x-y-z, x)
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:
>>> names = 'x y z' # or 'x, y, z'
>>> var(names)
(x, y, z)
>>> var(list('xyz'))
[x, y, z]
>>> var(set('xyz'))
{x, y, z}
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.