Push
Push

Reputation: 153

How can I convert a list of strings into sympy variables?

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

Answers (2)

smichr
smichr

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

timgeb
timgeb

Reputation: 78770

Several issues:

  1. The input string is never mutated by a call to sympy.symbols.
  2. You need to call symbols with every element of var as an argument, you hardcoded a call with the string argument 'i'.
  3. The assignment to 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

Related Questions