# I need help in complements of subsets

I have two subsets and tried this expression with MapThread:

TT := {{{P1}, {P2, P3}}}
XX := {P1, P2, P3, P4}

MapThread[Complement, {{Flatten[XX]}, {Flatten[TT]}}, 1]


{{P4}}

I need the partial sets' complements so that the outcome would be {{P2,P3,P4},{P1,P4}}

• Please add links to/from Wolfram Community cross-post. That way readers can see all prior responses and avoid duplication. Jan 6 at 17:12

## 3 Answers

You have too many braces in TTt. Note also, you should not use uppercase names, because these are used by the system.

Here is working code:

t = {{P1}, {P2, P3}};
x = {P1, P2, P3, P4};
Complement[x, #] & /@ t

{{P2, P3, P4}, {P1, P4}}


We could also use DeleteElements (new in 13.1)

a = {{P1}, {P2, P3}};
b = {P1, P2, P3, P4};

DeleteElements[b, #] & /@ a


{P2, P3, P4}, {P1, P4, P1}}

Unlike Complement, DeleteElements doesn't sort its output

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1};

DeleteElements[b, #] & /@ a


{{P4, P2, P1}, {P4, P3}}

Complement[b, #] & /@ a


{{P1, P2, P4}, {P3, P4}}

Unlike Complement, DeleteElements doesn't automatically delete duplicates. Therefore we must apply DeleteDuplicates to b

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1, P1};

DeleteElements[DeleteDuplicates @ b, #] & /@ a


{{P4, P2, P1}, {P4, P3}}

It should also be noted, that DeleteElements is much slower than Complement. But it is useful if we have short lists and want to preserve the original sort order.

Another way to preserve the original order is to use DeleteCases and Alternatives as follows:

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1};

DeleteCases[b, Alternatives @@ #] & /@ a

(*{{P4, P2, P1}, {P4, P3}}*)