5
$\begingroup$

Basically I need to do a set substraction operation A-B=C between two lists. For example, I have two lists A and B:

A = {{1,2,3,4},{3,4,3,4},{1,1,1,5},{1,2,1,2},{4,3,2,1}} 

B = {{1,2,1,2}, {1,2,3,4}}

and the result would be all the elements of A that do not appear in B and keeping the order of A:

C  = {{3,4,3,4},{1,1,1,5},{4,3,2,1}}

It is important to know that list B could be empty in some cases

I am also avoiding loops or recursion. Thank you all <3.

$\endgroup$
2
  • 2
    $\begingroup$ Look up Complement. It does not retain the order in A. $\endgroup$
    – Szabolcs
    Commented Oct 2, 2017 at 19:19
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$ Commented Oct 3, 2017 at 9:11

2 Answers 2

8
$\begingroup$

As @Szabolcs said with no order:

Complement[A, B]

{{1, 1, 1, 5}, {3, 4, 3, 4}, {4, 3, 2, 1}}

but to keep order you can try:

DeleteCases[A, Alternatives @@ B]

{{3, 4, 3, 4}, {1, 1, 1, 5}, {4, 3, 2, 1}}

You might need too look up levelspec option for DeleteCases depending on a situation. Some other ways to keep order

Delete[A, Position[A, Alternatives @@ B]]

Select[A, ! MemberQ[B, #] &]

with perhaps a few more others.

$\endgroup$
4
  • $\begingroup$ What about if list B is empty? $\endgroup$
    – Gabriela
    Commented Oct 2, 2017 at 20:53
  • 1
    $\begingroup$ @Gabriela did you check if these methods work with empty list? $\endgroup$ Commented Oct 2, 2017 at 21:38
  • 1
    $\begingroup$ @Gabriela, the nice thing about Mathematica is that as long as you know the function to use, questions on how it would behave for a particular case can be easily tried out by doing the experiments yourself. $\endgroup$ Commented Oct 2, 2017 at 23:41
  • $\begingroup$ @VitaliyKaurov yeah it works :D It did not work at first but was a mistake of mine, thank you so much. $\endgroup$
    – Gabriela
    Commented Oct 3, 2017 at 2:10
2
$\begingroup$
a = {{1, 2, 3, 4}, {3, 4, 3, 4}, {1, 1, 1, 5}, {1, 2, 1, 2}, {4, 3, 2, 1}};

b = {{1, 2, 1, 2}, {1, 2, 3, 4}};

Using DeleteElements and UniqueElements (both new in 13.1)

DeleteElements[a, b]

{{3, 4, 3, 4}, {1, 1, 1, 5}, {4, 3, 2, 1}}

First @ UniqueElements[{a, b}]

{{3, 4, 3, 4}, {1, 1, 1, 5}, {4, 3, 2, 1}}

"Both are much slower than Complement, but keep the sort order.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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