Reputation: 950
When I declare a single symbolic variable, it works:
>>> from sympy import var
>>> x = var('x')
>>> x + 2
x + 2
Now, for my purpose I need multiple variables, say, s0, s1, ..., s9
and I also need operations like s0 + 1
, s2 - s1
etc.
What will be the code? This will not work for me (EDIT: I mean I can do that, yeah, but for that I need to change my existing code a lot):
>>> from sympy import symbols
>>> s = symbols('s0:9'); s
(s0, s1, s2, s3, s4, s5, s6, s7, s8)
>>> s[0] + 1
s0 + 1
EDIT2: s0, s1, s2, s3, s4, s5, s6, s7, s8, s9 = symbols('s0:10')
is fine, but the number of variables is not fixed.
Upvotes: 1
Views: 4126
Reputation: 91620
First off, you should use symbols
instead of var
. var
does some magic to inject the Symbols into the namespace, and should only be used interactively.
If you want an arbitrary number of Symbols, you want the numbered_symbols
function, which produces an iterator. Here is the documentation. An example
>>> N = numbered_symbols('s')
>>> for s, _ in zip(N, range(10)):
... print(s)
s0
s1
s2
s3
s4
s5
s6
s7
s8
s9
Upvotes: 3
Reputation: 17552
This works just fine, not sure what problem you are having with this:
>>> from sympy import symbols
>>> s = symbols('s0:10')
>>> s
(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9)
>>> s[0] + 1
s0 + 1
If you want to set each to a variable, you can use multiple-assignment:
s0, s1, s2, s3, s4, s5, s6, s7, s8, s9 = symbols('s0:10')
This would be the equivalent of:
s0, s1 = Symbol('s0'), Symbol('s1') # and s2:s9 as well
Upvotes: 1