# Delete elements of a list that appear in another list

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.

• Look up Complement. It does not retain the order in A. – Szabolcs Oct 2 '17 at 19:19
• 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. – Vitaliy Kaurov Oct 3 '17 at 9:11

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.

• What about if list B is empty? – Gabriela Oct 2 '17 at 20:53
• @Gabriela did you check if these methods work with empty list? – Vitaliy Kaurov Oct 2 '17 at 21:38
• @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. – J. M. is in limbo Oct 2 '17 at 23:41
• @VitaliyKaurov yeah it works :D It did not work at first but was a mistake of mine, thank you so much. – Gabriela Oct 3 '17 at 2:10