# Difference of certain elements from two lists

I have two lists and I want to take the difference keeping the first elements of the sublists ( X1,X2 below) intact which are the same in both lists. Is there any easier way to do it without explicitly going through each list element and taking the differences except the first one? I tried

listA = {{1}, {X1, a, b}, {X2, c, d}};
listB = {{0}, {X1, a0, b0}, {X2, c0, d0}};
MapThread[{First[#1] , Rest[#1] - Rest[#2]} &, {listA, listB}]


Output:

{{1, {}}, {X1, {a - a0, b - b0}}, {X2, {c - c0, d - d0}}}


Expected output:

{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}


How do I remove these unwanted braces?

• Flatten[#, 1] & /@ MapThread[{First[#1], Rest[#1] - Rest[#2]} &, {listA, listB}]
– Syed
Dec 14, 2022 at 16:22
• I did use Flatten but as //Flatten which removed all the braces which is why it did not work. Dec 14, 2022 at 17:44
• MapThread[{First[#1], Sequence @@ (Rest[#1] - Rest[#2])} &, {listA, listB}] Dec 14, 2022 at 22:52
• If you have at least version 12.1 then consider also MapThread[{First[#1], Splice[Rest[#1] - Rest[#2]]} &, {listA, listB}] Dec 14, 2022 at 22:54

Try this:

 MapThread[
Flatten@{First[#1],
If[SameQ[Rest[#], {}], Nothing, Rest[#1] - Rest[#2]]} &, {listA, listB}]

al = {{1}, {X1, a, b}, {X2, c, d}};

bl = {{0}, {X1, a0, b0}, {X2, c0, d0}};


Just append {} :> Nothing to the solution proposed in the question:

MapThread[{First[#1], Rest[#1] - Rest[#2]} &, {al, bl}] /. {} :> Nothing


{{1}, {X1, {a - a0, b - b0}}, {X2, {c - c0, d - d0}}}

listA = {{1}, {X1, a, b}, {X2, c, d}};
listB = {{0}, {X1, a0, b0}, {X2, c0, d0}};


Expected output:

{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}

listA - listB // ReplacePart[{i_, 1} :> listA[[i, 1]]]


{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}