Python adding Counter objects with negative numbers fails

Question:

why do adding an empty counter to another with a negative value results in 0

from collections import Counter
a=Counter({'a':-1})
b=Counter()
print(a+b)

Result

Counter()

but if the counter added to the empty one has a positive value it works. How do I preserve those negative values?

Asked By: wrbp

||

Answers:

Because when you add counters together, any entry in the result with a total of zero or less is omitted by definition in the docs.

Here are the docs: https://docs.python.org/3/library/collections.html#collections.Counter:~:text=Several%20mathematical%20operations,zero%20or%20less.

So that this answer is self-contained, the docs read:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

Answered By: Sam Spade

Counter filters out the keys which have counts of zero or less. See the docs:

Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

However, the update method does preserve the mentioned values.

from collections import Counter


a = Counter({'a':-1})
b = Counter()
a.update(b)

print(a) # Counter({'a': -1})
Answered By: Preet Mishra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.