Reputation: 13
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
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
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