Search code examples
sympysubstitution

Sympy: substitute list of symbols with list of values in list of expressions


I have a list of expressions

Fa = [F0, F1, ... Fn]

, containing expressions like

F0 = 2*x0 + 5*x1 - x2
F1 = 3*x0 - x1

, with sympy symbols

SymList = [x0, x1, ... xn]

Now I have a list of values that I would like to "respectively" substitute into the symbols such as

ValList = [6, 19, ... 2]

, so that x0 is replaced by 6, x1 is replaced by 19 and so on, in each expression. How would one accomplish this?

I have tried

res = [[expr.subs({sym:val}) for expr in Fa] for sym, val in zip(SymList,ValList)]

, but this yields a list of lists with only one symbol substituted.


Solution

  • The following will create a Tuple of expressions with the values replaced.

    from sympy import Tuple
    Tuple(*Fa).xreplace(dict(zip(SymList, ValList)))
    

    If you want a list, then apply list to the result.