Get Symmetric Difference of Counters in Python 3.15

Get Symmetric Difference of Counters in Python 3.15

The Counter class from the collections module behaves as a multiset, supporting operations that combine or compare two collections by their counts. Union keeps the larger count for each element, intersection keeps the smaller one, and subtraction reports how much one counter exceeds another. None of them showed how much two counters differ.

Since Python 3.15, Counter supports the symmetric difference operator ^, which reports the difference in counts for every element.

from collections import Counter

a = Counter(apple=5, banana=2, cherry=3)
b = Counter(apple=2, banana=2, date=4)

print(a ^ b)  # Counter({'date': 4, 'apple': 3, 'cherry': 3})

The operation is defined as max(a[x], b[x]) - min(a[x], b[x]), which is the absolute difference between the two counts. For apple that gives 3, since one counter holds 5 and the other 2. For cherry and date, each appears in only one counter, so the missing side counts as zero and the full value is reported. The result omits banana because both counters hold 2.

Because the operation takes the absolute difference, it is symmetric: a ^ b and b ^ a produce the same result. This is what separates it from subtraction, which is one-directional and reports only what the left counter holds in excess, leaving out elements that exist solely in the right one.

Leave a Comment

Cancel reply

Your email address will not be published.