Search code examples
pythoncounternegative-integer

Python adding Counter objects with negative numbers fails


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?


Solution

  • 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})