sympypython-3.7

Initialize a variable number of sympy symbols


Whenever you want to work with the python package sympy, a package for symbolic calculation, you need to initialize the variables as

x, y, z = symbols('x y z')

For my application, the number of symbols, that I need, is not fixed. I only have the information, that I have to calculate with e.g. 4 variables.

Is there a smart way to write to e.g. initialize

a,b,c = symbols('a b c')

when I need three variables and

a,b,c,d,e = symbols('a b c d e')

when I need five variables? In case, that I need more variables than letters in the alphabet, the function should start to initialize

aa, ab, ac,... .

Solution

  • You can use slice notation in symbols to create numbered symbols like

    In [16]: symbols('a1:100')                                                                                                        
    Out[16]: 
    (a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈, a₉, a₁₀, a₁₁, a₁₂, a₁₃, a₁₄, a₁₅, a₁₆, a₁₇, a₁₈, a₁₉, a₂₀, a₂₁, a₂₂, a₂₃, a₂₄, a₂₅, a₂₆, a₂₇, a
    ₂₈, a₂₉, a₃₀, a₃₁, a₃₂, a₃₃, a₃₄, a₃₅, a₃₆, a₃₇, a₃₈, a₃₉, a₄₀, a₄₁, a₄₂, a₄₃, a₄₄, a₄₅, a₄₆, a₄₇, a₄₈, a₄₉, a₅₀, a₅₁, a₅₂, a₅₃,
     a₅₄, a₅₅, a₅₆, a₅₇, a₅₈, a₅₉, a₆₀, a₆₁, a₆₂, a₆₃, a₆₄, a₆₅, a₆₆, a₆₇, a₆₈, a₆₉, a₇₀, a₇₁, a₇₂, a₇₃, a₇₄, a₇₅, a₇₆, a₇₇, a₇₈, a₇
    ₉, a₈₀, a₈₁, a₈₂, a₈₃, a₈₄, a₈₅, a₈₆, a₈₇, a₈₈, a₈₉, a₉₀, a₉₁, a₉₂, a₉₃, a₉₄, a₉₅, a₉₆, a₉₇, a₉₈, a₉₉)
    

    Then if you want n symbols where n is an int you can do

    syms = symbols('a1:%d' % n)