Simple Python implementation of bag/multiset

Terry Reedy tjreedy at
Fri Jun 20 03:47:29 CEST 2008

MRAB wrote:
> While another thread is talking about an ordered dict, I thought I'd
> try a simple implementation of a bag/multiset in Python. Comments/
> suggestions welcome, etc.
> class bag(object):

I would prefer a logical rather than alphs order to the methods. 
Certainly, starting with __init__ is traditional and necessary for the 
reader to discover the implementation (delegation to a dict as _items. 
     Get/setitems should be read together.

An alternative is subclassing dict.  some methods, like __getitem__ 
would work as are.

>           return self
>     def __init__(self, iterable=None):
>         self._items = {}
>         if iterable is not None:
>             for item in iterable:
>                 self._items[item] = self._items.get(item, 0) + 1
>     def __ior__(self, other):


More information about the Python-list mailing list