Counter Class -- Bag/Multiset

Terry Reedy tjreedy at
Fri Jan 23 03:42:11 CET 2009

Chris Rebert wrote:
> On Thu, Jan 22, 2009 at 5:41 PM, Giovanni Bajo <rasky at> wrote:
>> On Thu, 22 Jan 2009 10:11:37 -0800, Raymond Hettinger wrote:
>>> The collections module in Python 2.7 and Python 3.1 has gotten a new
>>> Counter class that works like bags and multisets in other languages.
>>> I've adapted it for Python2.5/2.6 so people can start using it right
>>> away:
>>> Here's a link to the docs for the new class:
>> Hi Raymond,
>> * I'm not a native speaker, but why use the word "Counter"? A "counter"
>> to my ear sounds like a number that is increased each time an event
>> occurs; the website counter, eg, comes to mind. I can understanda its
>> meaning probably stretches to "an object that counts",

Yes, little clicker devices for instances.

>> but I really can't
>> think of it as a group of object, or a container of object.

Me neither.

>> Moreover, I
>> find it a much more useful abstraction the idea of a "multi-set" (that
>> is, a set where elements can appear with multiple cardinality), rather
>> than stressing the concept of "counting" how many times each element
>> appears in the set.
>> * I find it *very* confusing c.items() vs c.elements(). Items and
>> elements are synonymous (again, in my understanding of English).
> I concur and would like to say additionally that having Counter's
> len() be the number of *unique* items as opposed to just the number of
> items seems a bit counterintuitive.

bag/multiset/counter has been implemented as dict with items as keys and 
counts as values, and len(dict) = #keys, so unique items is what I 
expect.  Giving the bag a sum-of-counts attributes also might be nice, 

More information about the Python-list mailing list