Difference Between Two Lists with Many Duplicates in Python

Posted by Paul on Stack Overflow See other posts from Stack Overflow or by Paul
Published on 2011-11-12T17:32:55Z Indexed on 2011/11/12 17:50 UTC
Read the original article Hit count: 155

Filed under:

I have several lists that contain many of the same items and many duplicate items. I want to check which items in one list are not in the other list. For example, I might have one list like this:

l1 = ['a', 'b', 'c', 'b', 'c']

and one list like this:

l2 = ['a', 'b', 'c', 'b']

Comparing these two lists I would want to return a third list like this:

l3 = ['c']

I am currently using some terrible code that I made a while ago that I'm fairly certain doesn't even work properly shown below.

def list_difference(l1,l2):
    for i in range(0, len(l1)):
        for j in range(0, len(l2)):
            if l1[i] == l1[j]:
                l1[i] = 'damn'
                l2[j] = 'damn'
    l3 = []
    for item in l1:
        if item!='damn':
            l3.append(item)
    return l3

How can I better accomplish this task?

© Stack Overflow or respective owner

Related posts about python