Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I try to filter sublists of a list which match a pattern.

test = {{"String1", "a"}, {"String2", "b"}, {"String3", 
"a"}, {"String4", "a"}};

The result should be:

result = {{"String1", "a"}, {"String3", "a"}, {"String4", "a"}}

That means the first entry should be any String and the second should be "a".

I tried:

Select[test, (# == {_, "a"}) &]

Which evaluates to {}.

share|improve this question
add comment

3 Answers

up vote 14 down vote accepted

If you use Cases, then you can give the pattern directly

Cases[test, {_String, "a"}]

If you want to stick with Select you can do this as well but you have to transform your pattern match into a test function

Select[test, MatchQ[#, {_String, "a"}] &]
share|improve this answer
ah get it. Select needs an explicit test function. Thank you –  RMMA Aug 23 '13 at 10:04
add comment

Another possibility:

Pick[#, (Thread@#)[[2]], "a"] &@test
{{"String1", "a"}, {"String3", "a"}, {"String4", "a"}}
share|improve this answer
being curious: why do you use Thread, instead of e.g. Pick[#, #[[All, 2]], "a"] &@test? –  Pinguin Dirk Aug 23 '13 at 10:11
@Pinguin Dirk. Well... Yours is a neater way! Thanks –  TomD Aug 23 '13 at 10:14
Please notice that OP has said: "first entry should be any String" –  Kuba Aug 23 '13 at 12:44
But the OP did NOT say 'any string' (note the capital). –  TomD Aug 23 '13 at 12:50
My interpretation of the question is that the first value could be any one of "String1", "String2", "String3", "String4" (any first value). For example, what the OP tried was Select[test, (# == {_, "a"}) &]. No mention of string (lower-case) there. I know what my code does, btw. –  TomD Aug 23 '13 at 19:39
show 1 more comment

Another solution:

Select[test, Function[{x}, StringQ[x[[1]]] && x[[2]] == "a"]]
share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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