# Replace list of list according to second list

Given

p = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {11, 0}}


I want to replace parts according to a second list t1 if the first part is equal but the second part different (first parts in t1 always match first parts in p)

t1 = {{5, 1}, {11, 1}}


Which would give me

{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}


I can do it by

t2 = t1[[All, 1]];
t3 = Flatten[Position[p[[All, 1]], #] & /@ t2];
p[[t3]] = t1;
p


Any ideas for smarter ways (like Replace, ReplacePart, ReplaceList or Cases?

• Does Fold[Replace[#1, {#2[[1]], _} -> #2, {1}] &, p, t1] works for you ? Apr 21 at 6:24
• Yes,it does! Thanks! Apr 21 at 9:33

f = Values @ GroupBy[Join @ ##, First, Last] &;

f[p, t1]

{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

• Good solution! Great idea! Apr 21 at 10:28
☺ = # /. ({#, _} -> {##} & @@@ #2) &;

p ~ ☺ ~ t1

{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

pos = Position[p[[All, 1]], #] & /@ First /@ t1


{{{4}}, {{6}}}

ReplacePart[p, Thread[pos -> t1]]


{{2, 0}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

Slightly different p2 to include duplicates/same t1:

p2 = {{2, 0}, {11, 3}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {11, 0}}
t1 = {{5, 1}, {11, 1}}


Create a list of rules:

t2 = Replace[t1, {x_, y_} :> {x, Blank[]}, {1}]


{{5, _}, {11, _}}

{{5, _} -> {5, 1}, {11, _} -> {11, 1}}

Apply rules:

p2 /. rules


{{2, 0}, {11, 1}, {3, 0}, {4, 0}, {5, 1}, {8, 0}, {11, 1}}

I think this is more easily modifiable than my other approach.

• Very Good! I like your idea! Apr 22 at 0:47