'Sympy IndexedBase substitution

I am a bit confused how to use Indexed objects in Sympy. Suppose I have the following setup:

from sympy import *
x = IndexedBase('x')
i = Idx('i')
s = Sum(x[i], (i, 0, 5))
s

Output:

  5       
 ___      
 ╲        
  ╲       
  ╱   x[i]
 ╱        
 ‾‾‾      
i = 0

Which ofcourse is equal to

x[0] + x[1] + x[2] + x[3] + x[4] + x[5]

By doing s.doit(). Now, how do I substitute x with some range? I expected the following to work:

s.subs(x, list(range(6)))

But it does not do anything it would seem. However s.doit().subs(x[0], 0) works, but it will only substitute 1 element. Is it not intended to substitute IndexedBase with some list?



Solution 1:[1]

When using SymPy, there is one thing to always keep in mind: the only objects SymPy operates on is SymPy's object. Consider this example:

expr = x + 3
r = expr.subs(x, 2)
print(r, type(r))
5 <class 'sympy.core.numbers.Integer'>

Here, we passed a int number to subs, but SymPy internally converted it to an Integer number. Then, it performed the addition, producing the Integer number 5.

There are occasions in which the input parameter cannot be converted to something SymPy can understand. Your example is one such occasion. Let's use sympify (or its alias S) to verify how your list is going to be converted to a SymPy object:

l = list(range(6))
c = sympify(l)
type(c)
# out: list

As we can see, SymPy is unable to convert an object of type list, hence it is unable to use it. In short, this is the reason your code doesn't produce the correct output.

However, let's try the same trick with a tuple:

c = sympify(tuple(l))
type(c)
# out: Tuple

Here, SymPy converted a Python object of type tuple to a SymPy object of type Tuple. Now, the substitution should produce the correct result:

s.doit().subs(x, tuple(l))
# out: 15

Here are the most common SymPy objects the support iteration: Tuple, Matrix, Array.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Davide_sd