3
$\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
    $\begingroup$ Look up Complement. It does not retain the order in A. $\endgroup$ – Szabolcs Oct 2 '17 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$ – Vitaliy Kaurov Oct 3 '17 at 9:11
5
$\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$
  • $\begingroup$ What about if list B is empty? $\endgroup$ – Gabriela Oct 2 '17 at 20:53
  • 1
    $\begingroup$ @Gabriela did you check if these methods work with empty list? $\endgroup$ – Vitaliy Kaurov Oct 2 '17 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$ – J. M. will be back soon Oct 2 '17 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 Oct 3 '17 at 2:10

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.