# How do I drop a sublist containing a certain element from a list?

I have two lists:

a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
b = {11, 8, 13};


I'm looking for a clean way to drop all elements of a which contain an element from b. The desired output for this example would be

c = {{4, 5, 6}}

where a[[2]] and a[[3]] have been dropped because they contain elements 8 and 11 from b.

Any help would be greatly appreciated!

• c=DeleteCases[a, lis_ /; MemberQ[lis, Alternatives @@ b]]...
– ciao
Feb 5, 2017 at 4:24
• Awesome! Thanks so much! If you post this as a solution I'd love to give you credit. :) Feb 5, 2017 at 4:25
• Don't worry about it, but thanks for sentiment.
– ciao
Feb 5, 2017 at 4:28

## 2 Answers

a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {1, 2, 3}, {11, 12, 13}};
b = {11, 8, 13};

Select[a, DisjointQ[b, #] &]

Select[a, {} == b ⋂ # &]

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

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


DisjointQ introduced in Mathematica 10. Use the second line in earlier versions.

Actually the second line appears to be faster in every test I have performed so I would use it regardless of version. For example:

SeedRandom[1]

a = RandomInteger[999, {5000, 100}];
b = {11, 8, 13};

Select[a, DisjointQ[b, #] &]  // Length // RepeatedTiming

Select[a, {} == b ⋂ # &]      // Length // RepeatedTiming

{0.11, 3686}

{0.0286, 3686}


In this particular case using Alternatives falls somewhere in the middle:

Select[a, FreeQ[Alternatives @@ b]] // Length // RepeatedTiming

{0.0463, 3686}


Due to its early exit behavior in a case where most of the lists will be rejected it pulls ahead:

SeedRandom[1]

a = RandomInteger[99, {5000, 100}];

Select[a, {} == b ⋂ # &]             // Length // RepeatedTiming
Select[a, FreeQ[Alternatives @@ b]]  // Length // RepeatedTiming

{0.0291, 223}

{0.0247, 223}


ciao doesn't want to make the effort to write an answer, but it is better for a question to have an real answer than a comment answer, so here is his answer.

a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {1, 2, 3}, {11, 12, 13}};
b = {11, 8, 13};
DeleteCases[a, lis_List /; MemberQ[lis, Alternatives @@ b]]


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

• "ciao doesn't want to make the effort ...". Ouch, man, just ouch...
– ciao
Feb 5, 2017 at 5:25
• @ciao. Sorry that it hurts, but is it not the simple truth? Feb 5, 2017 at 5:31
• @ciao. I'll delete this answer if you would prefer to see it gone now that Mr.Wizard has answered Feb 5, 2017 at 6:39