Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


list1 = {{"a",1},{"b",2},{"c",3}} 

I would like to delete any pair in list1 that does not have a first element that belongs to list2.

Example 1: If list2 = {"b"}, Output = {{"b",2}}
Example 2: If list2 = {"A","b"}, Output = {{"a",1},{"b",2}}

Here's what I have so far:

DeleteCases[list1,{#,_}/; !StringMatchQ[#,list2, IgnoreCase -> True]&].

I know this won't work (because StringMatchQ doesn't accept a list of values to compare to as a parameter, which leads me to thinking I need to Map the function above to list2.

share|improve this question
up vote 4 down vote accepted

You've almost got it:

list1 = {{"a", 1}, {"b", 2}, {"c", 3}};
list2 = {"A", "b"};

test = StringMatchQ[#, Alternatives @@ list2, IgnoreCase -> True] &;

Cases[list1, {_?test, _}]
{{"a", 1}, {"b", 2}}

A key element is clearly Alternatives.
I used Cases rather than DeleteCases as that seemed simpler to me.

The first part of my post is in direct answer to your question. Summary: use Alternatives, not Map.

Borrowing from belisarius' answer, if one is going to use ToLowerCase I propose this:

Pick[list1, list1[[All, 1]], Alternatives @@ ToLowerCase @ list2]

If some of the elements of list1 are not all lower case then:

Pick[list1, ToLowerCase @ list1[[All, 1]], Alternatives @@ ToLowerCase @ list2]
share|improve this answer


list1 = {{"a", 1}, {"b", 2}, {"c", 3}};
f[list1_, list2_] := Select[list1, MemberQ[ToLowerCase /@ list2, #[[1]]] &]
f[list1, {"A", "b"}]

(* {{"a", 1}, {"b", 2}} *)
share|improve this answer
That's nice too. I'd +1 but I'm out of votes for the day. (Remind me tomorrow.) – Mr.Wizard Feb 21 '13 at 17:27
@Mr.Wizard Thanks :)I turned it to CW so neither of us will need to remember the nuisance :) – Dr. belisarius Feb 21 '13 at 17:29
@belisarius - Very nice, thanks! – tjm167us Feb 21 '13 at 17:43

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.