Subtracting two lists in Python
        Posted  
        
            by wich
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by wich
        
        
        
        Published on 2010-01-15T09:53:17Z
        Indexed on 
            2010/05/08
            15:28 UTC
        
        
        Read the original article
        Hit count: 277
        
In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I'd like to do something like c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b.
Note this is different from sets! I'm not interested in finding the difference of the sets of elements in a and b, I'm interested in the difference between the actual collections of elements in a and b.
I can probably work this out with a for loop, looking up the first element of b in a and then removing the element from b and from a, etc. But this doesn't appeal to me, I'd like to do this with list comprehension in a nice and easy way. Is this possible?
© Stack Overflow or respective owner