Suppose I have the following list

l={{"x","b","c"},{"y","a","d"},{"x","b","y"},{"x","y","c"}}

I want to go through the list l and delete elements whenever "x" and "y" appear both in a single sublist such that I get:

{{"x","b","c"},{"y","a","d"}}

Order does not matter, as long as "x" and "y" both exist.

  • 2
    Thanks for accepting an answer, but I think you were too hasty doing that. While accepting is one of the things to do after your question is answered, we recommend that users should test answers before voting and wait 24 hours before accepting the best one. That allows people in all timezones to answer your question and an opportunity for other users to point alternatives, caveats or limitations of the available answers. – rhermans Aug 9 at 17:02
up vote 5 down vote accepted

Something like the following?

l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}};
DeleteCases[l, {OrderlessPatternSequence["x", "y", ___]}]

(* Out: {{“x”, “b”, “c”}, {“y”, “a”, “d”}} *)
  • Thank you for this. – William Aug 9 at 16:49
  • @William you are very welcome. – MarcoB Aug 9 at 17:20
  • @William Upvoting and accepting suffices. Comments are only for improvement suggestions, not "private messaging". – user202729 Aug 10 at 3:00
DeleteCases[l, _?(ContainsAll[{"x", "y"}])]

{{"x", "b", "c"}, {"y", "a", "d"}}

A different solution using SubsetQ and Select. I also prefer ti limit the scope of the variable definitions using With or Module.

With[
 {
  l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}}
  },
 Select[l, Not[SubsetQ[#, {"x", "y"}]] &]
 ]
  • 2
    It's not documented, but SubsetQ supports an operator form, so you could eliminate the pure function and instead do Select[l, Not @* SubsetQ[{"x", "y"}]] – Carl Woll Aug 9 at 18:07
  • 1
    @CarlWoll Nice tip. I really wish ! SubsetQ[{"x", "y"}] would work however. – Mr.Wizard Aug 9 at 21:44

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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