# Counting Elements in Multiple Lists

How to build a table that counts how many times each element in mainlist occurs in lst1, lst2, lst3, lst4 and which lst1, lst2, lst3, lst4 contains that element. For example, in mainlist, element N6073 has count = 4 and N6073 appears in lst1, lst2, lst3, and lst4. In mainlist, element N12061 has count = 2 and N12061 appears in lst1, lst3.

mainlist = {N6073, N6019, N12061, N6025, N6065, N6071, N6039, N6077,
N53023, N22103, N38077, N12093, N12111, N12035, N22117, N12053,
N41005, N4019, N22051, N22105}
lst1 = {N12061, N12111, N4019, N41005, N53023, N6019, N6025, N6065,
N6073, N6077}
lst2 = {N12053, N12093, N22117, N6019, N6025, N6039, N6073}
lst3 = {N12061, N12111, N4019, N6065, N6071, N6073}
lst4 = {N22103, N4019, N6019, N6025, N6039, N6065, N6073}

• Join[lst1, lst2, lst3, lst4] // Counts Sep 28, 2020 at 1:57
• very nice and can you then identify which of the lst1, lst2, lst3, lst4 each element in the mainlist falls into? Sep 28, 2020 at 2:07

table = {#, Counts[Join[lst1, lst2, lst3, lst4]] @ # /. _Missing -> 0,
Function[x, Select[{"lst1", "lst2", "lst3", "lst4"},
MemberQ[x] @ ToExpression[#] &]] @ #} & /@ mainlist;

grid // Grid


Alternative approaches:

sa = SparseArray[Outer[Boole @* MemberQ,  {lst1, lst2, lst3, lst4}, mainlist, 1]];

parents = Extract[{"lst1", "lst2", "lst3", "lst4"},

table2 = Transpose[{mainlist, Total[sa, 1], parents}];
table2 == table

 True

rg = RelationGraph[MemberQ[ToExpression@#2, #] &,
mainlist, {"lst1", "lst2", "lst3", "lst4"}, VertexLabels -> "Name"]


table3 = {#, VertexDegree[rg, #], AdjacencyList[rg, #]} & /@ mainlist;
table3 == table

 True

• super clever ... awesome kglr and many thank you's ... prg Sep 28, 2020 at 2:20
Clear["*"];
mainlist = {N6073, N6019, N12061, N6025, N6065, N6071, N6039, N6077,
N53023, N22103, N38077, N12093, N12111, N12035, N22117, N12053,
N41005, N4019, N22051, N22105};
lst1 = {N12061, N12111, N4019, N41005, N53023, N6019, N6025, N6065,
N6073, N6077};
lst2 = {N12053, N12093, N22117, N6019, N6025, N6039, N6073};
lst3 = {N12061, N12111, N4019, N6065, N6071, N6073};
lst4 = {N22103, N4019, N6019, N6025, N6039, N6065, N6073};
Subtract[#, 1] & /@ Counts[Join[mainlist, lst1, lst2, lst3, lst4]]


The result is

<|N6073 -> 4, N6019 -> 3, N12061 -> 2, N6025 -> 3, N6065 -> 3,
N6071 -> 1, N6039 -> 2, N6077 -> 1, N53023 -> 1, N22103 -> 1,
N38077 -> 0, N12093 -> 1, N12111 -> 2, N12035 -> 0, N22117 -> 1,
N12053 -> 1, N41005 -> 1, N4019 -> 3, N22051 -> 0, N22105 -> 0|>
`