Use SymPy to substitute elements into a summation?

I have been having good experiences with SymPy, but I’m still figuring out a few things.

One thing I am not clear on is how to substitute collections into an iterate operation, like a summation.

If I have a summation operation declared symbolically, how do I take a standard collection of numbers and substitute them to be summed?

from sympy import *

# We are going sum these items 
# by plugging into symbolic summation
items = [0, 5, 6, 2, 7]

# declare Sympy variables 
i, n = symbols('i n')
x = symbols('x', cls=Function)

# declare summation
f = Sum(x(i), (i, 0, n))

# how to iterate and sum items? 
f.subs(???) 

Answer

You defined x as a function. You can replace it with a function that picks up elements of the items list. You also need to substitute n to specify the upper limit of the summation:

from sympy import *

# We are going sum these items
# by plugging into symbolic summation
items = [0, 5, 6, 2, 7]

# declare Sympy variables
i, n = symbols('i n')
x = symbols('x', cls=Function)

# declare summation
f = Sum(x(i), (i, 0, n))

f.subs(n, len(items) - 1).doit().replace(x, lambda i: items[i])

Alternatively, you could define x as an IndexedBase instance and then make substitutions for all x[i] objects:

from sympy import *

# We are going sum these items
# by plugging into symbolic summation
items = [0, 5, 6, 2, 7]

# declare Sympy variables
i, n = symbols('i n')
x = IndexedBase('x')

# declare summation
f = Sum(x[i], (i, 0, n))

f.subs(n, len(items) - 1).doit().subs({x[i]: val for i, val in enumerate(items)})