Reputation: 153
I have a list of strings, e.g., var = ['x', 'y', 'z']
. I want to use these strings as sympy 'symbols'. I am trying to do this:
for i in var:
i = symbols('i')
it's not working of course. Can someone help me with this?
Upvotes: 4
Views: 1425
Reputation: 19115
The reason what you did did not work is because you tried to assign a symbol to a string which can't be changed (e.g. 'a' = 1 will fail for the same reason).
If you are working interactively and want variables with the same name as the symbols you can write
>>> var(','.join(variables)) # variables = ['x', 'y', 'z']
(x, y, z)
On a related note, sometimes you sympify an expression and would like to also have access to the variables, interactively. You can use var
for this, too:
>>> eq = S('x + y')
>>> var(','.join([s.name for s in eq.atoms(Symbol)]))
(x, y)
>>> eq.diff(x)
1
Upvotes: 2
Reputation: 78770
Several issues:
sympy.symbols
.symbols
with every element of var
as an argument, you hardcoded a call with the string argument 'i'
.i
inside the loop body is pointless because in the next iteration the name i
will be reassigned to the next element from var
(which you don't even use).So in summary, you need to call symbols
with every element of var
and store the return values somewhere.
>>> import sympy
>>> var_as_strings = ['x', 'y', 'z']
>>> var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
>>> var_as_symbol_objects
[x, y, z]
>>> type(var_as_symbol_objects[0])
<class 'sympy.core.symbol.Symbol'>
(I used overly verbose variable names to be make the example self-documenting.)
Upvotes: 3