2

I would like to know how to get the symmetric difference between two lists.

For example:

list1 = ['a','a','b','c','d']    
list2 = ['a','b','c','f']    
sym_dif = ['a', 'd', 'f']

Sets don't work because I have multiple instances of the same object in each list. I've tried browsing Stackoverflow and the internet and everyone always suggests sets. Maybe symmetric difference isn't what I'm looking for? I'm just looking for each item which appears in only one list or appears more in one list than the other.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Her0Her0
  • 486
  • 1
  • 4
  • 12

1 Answers1

3

You can use collections.Counter instead:

from collections import Counter
c1 = Counter(list1)
c2 = Counter(list2)
print(list((c1 - c2 | c2 - c1).elements()))

This outputs:

['a', 'd', 'f']
blhsing
  • 91,368
  • 6
  • 71
  • 106