8

I am trying to define a lot of variables in "sympy" for symbolic processing.

import sympy as sp

b_0 = sp.symbols('b_0')
b_1 = sp.symbols('b_1')
...
b_X = sp.symbols('b_X')

and so on with the X going from 1 to 1000.

Is there an easy way to do it?

B. Willems
  • 80
  • 1
  • 7
stormer1120
  • 97
  • 1
  • 5

2 Answers2

7

There are a few options:

>>> sp.symbols('b_0:10')
(b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9)

or, using a formatted string,

>>> n = 10
>>> sp.symbols('b_0:{}'.format(n))
(b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9)

These return a tuple of symbols. There are more formatting options: see symbols docs.

There is also a function to generate a NumPy array of symbols:

>>> sp.symarray('b', 10)
array([b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9], dtype=object)

All of these examples are meant to be assigned to something. For example, b = sp.symbols('b_0:10') assigns the tuple of symbols to b, so they can be accessed as b[0], b[1], etc. SymPy symbols are not accessed by the string representing them, such as "b_0" or "b_1".


Finally, there are Indexed objects in case you need an array of symbols of undetermined size: Indexed objects are created on the fly as you use A[n] notation with A being an IndexedBase.

  • Thank you for your reply! `sp.symarray('A',10) B=sp.diff(A,A_1)` when i try this it says the A_1 is undefined. the other methods also say A_1 is undefined. I am looking for a way to get the python 2.7 to acknowledge the created variables. – stormer1120 Mar 13 '18 at 00:56
  • These are supposed to be assigned to something. I edited the answer. Take note of the difference between Python variable name and SymPy symbol name. –  Mar 13 '18 at 01:02
2

If you want to still be able to call individuals symbols, like b_0:

Since:

from sympy import symbols

# Number of symbols you need
X = 5

b = symbols(f"b_0:{X}")
>>> b
(b_0, b_1, b_2, b_3, b_4)

>>> b_0
NameError: name 'b_0' is not defined

You could add them to the local variables through a dictionary:

from sympy import symbols

# Number of symbols you need
X = 5

# To still have b[i]
b = symbols(f"b_0:{X}")

b_dict = {f"b_{i}": b[i] for i in range(X)}
locals().update(b_dict)
Owen
  • 56
  • 1
  • 8
  • Since this exercise is about DRY, b_dict can be created without repeating the schema: `b_dict = {str(symbol):symbol for symbol in b}` – Don Hatch May 18 '23 at 08:58
  • Hmm, [sympy.var()](https://docs.sympy.org/latest/modules/core.html#sympy.core.symbol.var) seems to be a perfect solution to the question, except that it apparently injects the variables into globals() instead of locals(), making it useless if we want modular code. How annoying. – Don Hatch May 18 '23 at 09:13