# How to select elements from a list of pairs based on first element belonging to a different list?

This is my very first question and I really appreciate this ability and thankful the community.

I have two lists and need to select only those pairs from the first list, first element of which is present in the second list:

I have:

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5};


I need to get

{{1, "a"}, {3, "c"}, {5, "e"}}


A short cut:

Extract[listA, List /@ listB]


{{1, "a"}, {3, "c"}, {5, "e"}}

Position[listA[[All,1]], Alternatives@@listB]//Extract[listA,#]&

(* {{1, a}, {3, c}, {5, e}} *)


One of many ways

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5};
Select[listA,MemberQ[listB,First[#]]&]


• this is precisely what I was looking for! Thank you! Commented Nov 30, 2022 at 5:03

Here is one way to do it:

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5};
DeleteCases[listA, _?(! MemberQ[listB, First@#] &)]


OR

Cases[listA, {a_, _} /; MemberQ[listB, a]]


OR

Select[listA, IntersectingQ[{First@#}, listB] &]


Result:

{{1, "a"}, {3, "c"}, {5, "e"}}

• Thank you, Syed. This works, but I was playing with Select and am happy Nasser has a solution I was looking for! Commented Nov 30, 2022 at 5:04
• Sorry, I did not notice the other two methods you listed. Perfect! Thank you Commented Nov 30, 2022 at 5:19
• @IgorBinder, please wait for a day and then select an answer. What is perfect for one scenario may not be so for another.
– Syed
Commented Nov 30, 2022 at 5:24

Using Cases, FreeQ and Condition:

Cases[listA, {x_, y_} /; ! FreeQ[listB, x]]
(*{{1, "a"}, {3, "c"}, {5, "e"}}*)

☺ = #[[#2]] &;

listA ~☺~ listB

{{1, "a"}, {3, "c"}, {5, "e"}}


Here we can use <| |>

{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}} //
Rule@@@#& //
Apply[Association] //
KeyTake[{1,3,5}] //
KeyValueMap[List]


{{1, a}, {3, c}, {5, e}}

• (With the caveat that you need the keys (first entry in the list) to be unique; if they are not, then entries may be lost.) Commented Dec 1, 2022 at 18:03
• @JoshuaSchrier in that case, for example, <| 1 -> {"a", "b"} |> could work for dup keys. Commented Dec 2, 2022 at 4:58