Suppose I have the following list


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:


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

  • 2
    $\begingroup$ 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. $\endgroup$ – rhermans Aug 9 '18 at 17:02

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”}} *)
  • $\begingroup$ Thank you for this. $\endgroup$ – William Aug 9 '18 at 16:49
  • $\begingroup$ @William you are very welcome. $\endgroup$ – MarcoB Aug 9 '18 at 17:20
  • $\begingroup$ @William Upvoting and accepting suffices. Comments are only for improvement suggestions, not "private messaging". $\endgroup$ – user202729 Aug 10 '18 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.

  l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}}
 Select[l, Not[SubsetQ[#, {"x", "y"}]] &]
  • 2
    $\begingroup$ 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"}]] $\endgroup$ – Carl Woll Aug 9 '18 at 18:07
  • 1
    $\begingroup$ @CarlWoll Nice tip. I really wish ! SubsetQ[{"x", "y"}] would work however. $\endgroup$ – Mr.Wizard Aug 9 '18 at 21:44

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.