SymPy – Symbols

Symbol is the most important class in symPy library. As mentioned earlier, symbolic computations are done with symbols. SymPy variables are objects of Symbols class.

Symbol() function’s argument is a string containing symbol which can be assigned to a variable.

>>> from sympy import Symbol 
>>> x=Symbol('x') 
>>> y=Symbol('y') 
>>> expr=x**2+y**2 
>>> expr

The above code snippet gives an output equivalent to the below expression −

x2+y2x2+y2

A symbol may be of more than one alphabets.

>>> s=Symbol('side') 
>>> s**3

The above code snippet gives an output equivalent to the below expression −

side3side3

SymPy also has a Symbols() function that can define multiple symbols at once. String contains names of variables separated by comma or space.

>>> from sympy import symbols 
>>> x,y,z=symbols("x,y,z")

In SymPy’s abc module, all Latin and Greek alphabets are defined as symbols. Hence, instead of instantiating Symbol object, this method is convenient.

>>> from sympy.abc import x,y,z

However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with more than one alphabets are not defined in abc module, for which you should use Symbol object as above. The abc module defines special names that can detect definitions in default SymPy namespace. clash1 contains single letters and clash2 has multi letter clashing symbols

>>> from sympy.abc import _clash1, _clash2 
>>> _clash1

The output of the above snippet is as follows −

{‘C’: C, ‘O’: O, ‘Q’: Q, ‘N’: N, ‘I’: I, ‘E’: E, ‘S’: S}

>>> _clash2

The output of the above snippet is as follows −

{‘beta’: beta, ‘zeta’: zeta, ‘gamma’: gamma, ‘pi’: pi}

Indexed symbols can be defined using syntax similar to range() function. Ranges are indicated by a colon. Type of range is determined by the character to the right of the colon. If itr is a digit, all contiguous digits to the left are taken as the nonnegative starting value. All contiguous digits to the right are taken as 1 greater than the ending value.

>>> from sympy import symbols 
>>> symbols('a:5')

The output of the above snippet is as follows −

(a0, a1, a2, a3, a4)

>>> symbols('mark(1:4)')

The output of the above snippet is as follows −

(mark1, mark2, mark3)

Leave a Reply