Replace doesn't return expected output within Table

FirstList = {{1, 2, x}, {2, 3, x}, {4, 2, x}, {x, 3, 5}, {x, 7, 8}};
SecondList = {a, b, c, d, e};
Table[
Replace[Part[FirstList, n], x -> Part[SecondList, n]], {n, Length[SecondList]}]

{{1, 2, x}, {2, 3, x}, {4, 2, x}, {x, 3, 5}, {x, 7, 8}}


I expected the output to be

{{1, 2, a}, {2, 3, b}, {4, 2, c}, {d, 3, 5}, {e, 7, 8}}


How do you make it so?

The level specification of Replace is wrong. Compare:

Replace[x, x -> a]
Replace[{1, 2, x}, x -> a]
Replace[{1, 2, x}, x -> a, {1}]

Out[14]= a

Out[15]= {1, 2, x}

Out[16]= {1, 2, a}


So to make this work, add a level specification to Replace:

Table[Replace[Part[FirstList, n], x -> Part[SecondList, n], {1}], {n, Length[SecondList]}]


You can also use ReplaceAll, which operates at every level. In general, though, I prefer Replace where possible over the scattershot approach of ReplaceAll.

ReplaceAll (operator form: /.) automatically moves through all levels, so in this case it will do its replacements at level 1 and give the result you want.

a1 = {{1, 2, x}, {2, 3, x}, {4, 2, x}, {x, 3, 5}, {x, 7, 8}};
a2 = {a, b, c, d, e};
MapThread[(#1 /. x -> #2) &, {a1, a2}]

{{1, 2, a}, {2, 3, b}, {4, 2, c}, {d, 3, 5}, {e, 7, 8}}

• I think it's a bit misleading to say "ReplaceAll works at level 1 by default", because ReplaceAll does not have a level spec and works on every level (not just level 1). – Sjoerd Smit Mar 7 '18 at 14:01
• @SjoerdSmit. Good point. I should have written "starts at". I have made this correction. – m_goldberg Mar 7 '18 at 14:07
• But ReplaceAll  also works at level 0... Or am I confusing level specs with positions here? – Sjoerd Smit Mar 7 '18 at 14:15
• To clarify: compare Replace[x, x -> 1, {0}] with ReplaceAll[x, x -> 1]. Both do the replacement, which happens at level 0. – Sjoerd Smit Mar 7 '18 at 14:19
• @SjoerdSmit. You're right. I seem to be having one of my muddle headed days. I think I've got the wording right this time. But if you think not, please keep working on putting me straight. – m_goldberg Mar 7 '18 at 15:02