# How can I list the common elements of two lists?

The elements of both lists are given as

A={9,5,9,3}, B={9,9,5,5}

In this case, how can I list the list {9,5,9} of the common elements of the two lists?

(The order does not matter.)

If you need the duplicate 9 in the output:

 In[1]:= Flatten[KeyValueMap[ConstantArray, Merge[KeyIntersection[Counts /@ {{9, 5, 9, 3}, {9, 9, 5, 5}}], Min]], 1]
Out[1]:= {9, 9, 5}


If you didn't need the duplicate 9 you could just use the Intersection function.

• Thank you. It was helpful.
– Milk
Commented Jun 8, 2021 at 1:49
a = {9, 5, 9, 3};

b = {9, 9, 5, 5};


Using DeleteElements and SymmetricDifference (both new in 13.1)

DeleteElements[a, SymmetricDifference[a, b]]


{9, 5, 9}

Another test:

a = {0, 9, 5, 9, 3, 3, 4, 4, 4, 4, 7};

b = {9, 9, 5, 5, 0, 8};

DeleteElements[a, SymmetricDifference[a, b]]


{0, 9, 5, 9}

a = {9, 5, 9, 3};

b = {9, 9, 5, 5};


Using DeleteCases:

DeleteCases[a, Alternatives @@ DeleteCases[a, Alternatives @@ b]]

(*{9, 5, 9}*)


Grabbing the @eldo's second test:

a = {0, 9, 5, 9, 3, 3, 4, 4, 4, 4, 7};

b = {9, 9, 5, 5, 0, 8};

DeleteCases[a, Alternatives @@ DeleteCases[a, Alternatives @@ b]]

(*{0, 9, 5, 9}*)


Using the ResourceFunction IntersectionWithDuplicates:

A = {9, 5, 9, 3};
B = {9, 9, 5, 5};

ResourceFunction[
"IntersectionWithDuplicates"][A,B]


{5,9,9}

The function admittedly sorts the output as stated in the description.