Search code examples
python-3.xlistrepeat

Find Common Items Between Two Lists With Repeated Elements Using Python 3


A lot of posts or How to find list intersection? aim to find to unique items between two lists:

Here are my two lists:

list1=[1, 2, 2, 3, 3, 4, 4, 5, 10, 12] 
list2=[1, 1, 2, 2, 3, 4, 4, 5, 8, 18]

my answer is to find common items, the items can be repeated. for example, one 1 appears in those two lists, therefore, res should contain one 1. Two 2 appear in the two lists, res should contain two 2, etc.

res = [1 ,2, 2, 3, 4, 4, 5]

The order does not matter, my attempt is to use:

res = [x for x in list2 if x in list1]
# res = [1, 1, 2, 2, 3, 4, 4, 5] by above code

However, it is not correct, so how can I do that?


Solution

  • The only way I could think to do this is by removing items from list2 as you go:

    list1 = [1, 2, 2, 3, 3, 4, 4, 5, 10, 12]
    list2 = [1, 1, 2, 2, 3, 4, 4, 5, 8, 18]
    
    res = []
    
    for x in list1:
        if x in list2:
            res.append(x)
            list2.remove(x)
    
    print(res)
    

    I'm curious if there are better answers out there.