I want to make a selection on this list

words = {{{"word1", "word2"}, 19}, {{"word1", "word3"}, 
   8}, {{"word1", "word4"}, 7}, {{"word2", "word5"}, 
   7}, {{"word2", "word5"}, 7}, {{"word3", "word6"}, 
   7}, {{"word3", "word7"}, 7}, {{"word3", "word8"}, 
   6}, {{"word4", "word6"}, 6}};

From this list, I want to select all 'records' which have one of these words

wordsselect = {"word2", "word4", "word8"}

The desirde output is:

wordsnew = {{{"word1", "word2"}, 19}, {{"word1", "word4"}, 
   7}, {{"word2", "word5"}, 7}, {{"word2", "word5"}, 
   7}, {{"word3", "word8"}, 6}, {{"word4", "word6"}, 6}}

I tried to make a selection based on one word

Select[words[[All, {1, 2}]], MemberQ[#[[1]], "word2"] &]

this works fine. So I tried the next script

Select[words[[All, {1, 2}]], MemberQ[#[[1]], wordsselect ] &]

The output is empty {}

I have two questions:

  1. How do I get the desired output?

  2. Why is my second try not working?

  • 6
    $\begingroup$ Try Alternatives@@wordsselect instead. This will be a real pattern involving alternatives. Your pattern matches with any list that exactly equals the list of three words. $\endgroup$ Jul 13, 2015 at 20:59

5 Answers 5


As already noted the second argument of MemberQ needs to be a pattern or literal expression; Alternatives can be used here.

Another method is to use IntersectingQ instead:

Select[words, IntersectingQ[#[[1]], wordsselect] &]
{{{"word1", "word2"}, 19}, {{"word1", "word4"}, 7},
 {{"word2", "word5"}, 7}, {{"word2", "word5"}, 7},
 {{"word3", "word8"}, 6}, {{"word4", "word6"}, 6}}
  • $\begingroup$ thank you again finding yet another useful function I was not aware of: IntersectingQ...my blindspot seems ever increasing as my time is ever decreasing...+1 :) $\endgroup$
    – ubpdqn
    Jul 14, 2015 at 12:55
  1. This one should work:

Select[words, Or @@ (MemberQ[wordsselect, #] & /@ #[[1]]) &]

It checks for each one of the words in the first list-element. If there is at least one word in the wordsselect list then the whole element is selected.

  1. With MemberQ[#[[1]], wordsselect ] & you are checking if the list wordsselect is inside each {"wordX","wordY"}
Select[words, MemberQ[#[[1]], "word1" | "word2" | "word8"] &]

Just for something different:

Flatten[Last@Reap[Sow[{##}, #1] & @@@ words, wordsselect, #2 &], 2]

Pre v10 without IntersectingQ you can do this:

 Select[words, Length@Intersection[#[[1]], wordsselect] > 0 &]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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