How to Find the Difference Between 3 Lists That May Have Duplicate Numbers

advertisements

This question already has an answer here:

  • Difference Between Two Lists with Duplicates in Python 4 answers

I have 3 lists and I want to find the difference between the 1st/2nd and 2nd/3rd and print them.

Here is my code:

n1 = [1,1,1,2,3]
n2 = [1,1,1,2] # Here the 3 is not found ("3" is not present in n1 at all)
n3 = [1,1,2]   # here 1 is not found (there are fewer "1"s in n3 than in n2)
for x in n1:
   if x not in n2:
      print x
for m in n2:
   if m not in n3:
      print m

but i get only 3 as output.

How to make it output 1 and 3? I tried using sets as well, but it only printed 3 again.


Since you seem to care about the number of times an item is found in both lists, you need to either remove matched items from the list you're comparing with:

comp = n2[:]  # make a copy
for x in n1:
    if x not in comp:
        print x
    else:
        comp.remove(x)
# output: 3

or use a collections.Counter

from collections import Counter
print Counter(n1) - Counter(n2)
# output: Counter({3: 1})

which tells you which items in n1 are not in n2 or can be found more often in n1 than in n2.

So, for example:

>>> Counter([1,2,2,2,3]) - Counter([1,2])
Counter({2: 2, 3: 1})