# How to return matching sublists or empty list

How to return matching sublists or empty list

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{1, 0.5}, {0, 0.4}, {0, 0.1}};
Commonest[Join[m1, m2]]


out:

{{1, 0.5}}


But it fails to return 0 or empty list as the lists do not match

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{0, 0.5}, {0, 0.4}, {0, 0.1}};
Commonest[Join[m1, m2]]


out:

{{1, 0.5}, {2, 0.4}, {3, 0.1}, {0, 0.5}, {0, 0.4}, {0, 0.1}}


how to return empty list?

• Perhaps If[(c = Commonest[Join[m1, m2]]) === Join[m1, m2], {}, c]? Dec 4, 2013 at 8:08

Intersection[m1,m2]


will deal with common elements and return "empty set" if no common elements. More complex list structures may require modification.

Try the following.

This are your lists to try on:

m1 = {{1, 0.5}, {2, 0.4}, {3, 0.1}};
m2 = {{1, 0.5}, {0, 0.4}, {0, 0.1}};
m3 = {{2, 0.5}, {0, 0.4}, {0, 0.1}};
m4 = {{1, 0.5}, {2, 0.4}, {0, 0.1}};


This is the function to do the job on one element:

f[x_] := Select[m1, #1 == x &];

f[{1, 0.5}]

(*  {{1, 0.5}} *)


This is how it works on the list:

Flatten[f /@ m2, 1]

(*  {{1, 0.5}} *)


then

Flatten[f /@ m4, 1]

(* {{1, 0.5}, {2, 0.4}}  *)


and

Flatten[f /@ m3, 1]

(*  {}  *)


Have fun.