Renegade Renegade - 4 months ago 13
Python Question

Intersection of two lists including duplicates?

>>> a = [1,1,1,2,3,4,4]
>>> b = [1,1,2,3,3,3,4]


Please note this is not the same question as this:
Python intersection of two lists keeping duplicates
Because even though there are three 1s in list a, there are only two in list b so the result should only have two.


You can use collections.Counter for this, which will provide the lowest count found in either list for each element when you take the intersection.

from collections import Counter

c = list((Counter(a) & Counter(b)).elements())


[1, 1, 2, 3, 4]