2
$\begingroup$
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?

$\endgroup$
5
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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}}
$\endgroup$
5
  • 1
    $\begingroup$ 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). $\endgroup$ – Sjoerd Smit Mar 7 '18 at 14:01
  • $\begingroup$ @SjoerdSmit. Good point. I should have written "starts at". I have made this correction. $\endgroup$ – m_goldberg Mar 7 '18 at 14:07
  • $\begingroup$ But ReplaceAll also works at level 0... Or am I confusing level specs with positions here? $\endgroup$ – Sjoerd Smit Mar 7 '18 at 14:15
  • 1
    $\begingroup$ To clarify: compare Replace[x, x -> 1, {0}] with ReplaceAll[x, x -> 1]. Both do the replacement, which happens at level 0. $\endgroup$ – Sjoerd Smit Mar 7 '18 at 14:19
  • $\begingroup$ @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. $\endgroup$ – m_goldberg Mar 7 '18 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.