user1618063
user1618063

Reputation: 13

How do you compare 2 lists and return the difference? (difference function in python does not return what I need)

I am trying to find the difference between 2 lists. Basically, I want to know everything that is in list 1 that is not in list 2. The best way to explain it, is with an example:

List1 = [a, a, b, c, d, e]
List2 = [a, b, c, d]

In this example, I would like a function that would return [a, e]

When I use the difference function in python, it will only return "e" and not that there is an additional "a" that is in list 1. When I simply used XOR between the 2 lists, it also only returned "e."

Upvotes: 1

Views: 254

Answers (2)

jterrace
jterrace

Reputation: 67073

What you want is really not set subtraction. You can use a Counter:

>>> List1 = ['a', 'a', 'b', 'c', 'd', 'e']
>>> List2 = ['a', 'b', 'c', 'd']
>>> import collections
>>> counter = collections.Counter(List1)
>>> counter.subtract(List2)
>>> list(counter.elements())
['a', 'e']

Upvotes: 8

Waleed Khan
Waleed Khan

Reputation: 11467

Assuming List1 is a strict superset of List2:

for i in List2:
    if i in List1:
        List1.remove(i)
# List1 is now ["a", "e"]

(You can clone List1 if you don't want to do it in-place.)

Upvotes: 1

Related Questions