Counter Class -- Bag/Multiset

Giovanni Bajo rasky at
Fri Jan 23 13:05:02 CET 2009

On 1/23/2009 2:49 AM, 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", but I really can't
>> think of it as a group of object, or a container of object. 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.

In fact, I think that it makes sense when you're stressing the fact that 
it's just a dictionary of objects and their counters (which the name 
"Counter" in fact stresses).

And my main objection is exactly this: a multiset is a differnt abstract 
data structure (which is probably worth its own ABC in Python); the fact 
that can be implemented through a mapping of objects and counters is 
just its concrete implementation. This was perfectly represented by 
Raymond's previous bag class, that was *using* a dictionary instead of 
*being* a dictionary.
Giovanni Bajo
Develer S.r.l.

More information about the Python-list mailing list