Lagrange form of the interpolating polynomial I

Clear[f, x, p];
f[x_] = Exp[-x];
xlist = {0. , 1. , 2. };
ylist = f[xlist];
n = Length[xlist];
l[k_, x_] := 
        Product[(x - xlist[[i]])/(xlist[[k]] - 
                  xlist[[i]]), {i, 1, 
              k - 1}]*
Product[(x - 
                  xlist[[i]])/(xlist[[k]] - 
                  xlist[[i]]), {i, k + 1, 
              n}];
p[x_] = Sum[ylist[[k]]*l[k, x], {k, 1, n}];

p[x]

Collect[p[x], x]

Plot[{f[x], p[x]}, {x, 0, 2}, 
      PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]

Lagrange form of the interpolating polynomial II

Below is a variation on the code from above.  In the version above, the Lagrange polynomials (Subscript[L, n, k])(x) are defined as functions of the index k and the variable x.  This makes it a bit messy to deal with derivatives of (Subscript[L, n, k])(x) when it comes to extending the code to compute Hermite interpolating polynomials.  In the version below, (Subscript[L, n, k])(x) is defined as a list.  Each element in the list is a function of x and the list index is k.  When it comes to extending this to computing Hermite interpolating polynomials, you can just use l'[x] for the relevant derivative.  (Note that l'[x] is a list.  To get the kth element in the list, use l'[x][[k]].)

Clear[f, x, p, xlist, ylist, l];
f[x_] = Exp[-x];
xlist = {0. , 1. , 2. };
ylist = f[xlist];
n = Length[xlist];
l[x_] = 
        Table[Product[(x - xlist[[i]])/(xlist[[k]] - 
                    xlist[[i]]), {i, 1, 
                k - 1}]*
Product[(x - 
                    xlist[[i]])/(xlist[[k]] - 
                    xlist[[i]]), {i, k + 1, n}], 
{k, 
            1, n}];
p[x_] = 
        Sum[ylist[[k]]*l[x][[k]], {k, 1, n}];

p[x]

Collect[p[x], x]

Plot[{f[x], p[x]}, {x, 0, 2}, 
      PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]

To see what the code is doing, we can look at l[x] and see that it is a list.

l[x]