Real-world use of Counter

Ethan Furman ethan at
Wed Nov 5 17:26:52 CET 2014

I'm looking for real-world uses of collections.Counter, specifically to see if anyone has been surprised by, or had to 
spend extra-time debugging, issues with the in-place operators.


Most Python data types will cause a TypeError to be raised if unusable types are passed in:

--> {'a': 0}.update(5)
TypeError: 'int' object is not iterable

--> [1, 2, 3].extend(3.14)
TypeError: 'float' object is not iterable

--> from collections import Counter
--> Counter() + [1, 2, 3]
TypeError: unsupported operand type(s) for +: 'Counter' and 'list'

Most Counter in-place methods also behave this way:

--> c /= [1, 2, 3]
TypeError: unsupported operand type(s) for /=: 'Counter' and 'list'

However, in the case of a handful of Counter in-place methods (+=, -=, &=, and |=), this is what happens instead:

--> c = Counter()
--> c += [1, 2, 3]
AttributeError: 'list' object has no attribute 'items'

Even worse (in my opinion) is the case of an empty Counter `and`ed with an incompatible type:

--> c &= [1, 2, 3]

No error is raised at all.

In order to avoid unnecessary code churn (the fix itself is quite simple), the maintainer of the collections module 
wants to know if anybody has actually been affected by these inconsistencies, and if so, whether it was a minor 
inconvenience, or a compelling use-case.

So, if this has bitten you, now is the time to speak up!  :)


More information about the Python-list mailing list