[Python-ideas] question - 'bag' type

Chris Rebert pyideas at rebertia.com
Thu Apr 15 07:14:11 CEST 2010

On Wed, Apr 14, 2010 at 10:02 PM, C. Titus Brown <ctb at msu.edu> wrote:
> Hi all,
> this seems like the right forum to ask -- is there a reason why Python
> doesn't have a 'bag' builtin type, e.g.
>   b = bag(foo=bar, baz=bif)
>   assert b.foo == bar
>   assert b.bz == bif
> ?
> It's easy to write and there's a great discussion over at the cookbook:
> http://code.activestate.com/recipes/259174-bag-collection-class/
> Inquiring minds want to know!

There was some discussion:

...the outcome of which was the Counter class:

It's /somewhat/ like a bag, except elements can have negative
multiplicity and the default iterator yields each element exactly
once, regardless of its multiplicity (yeah, I know, doesn't quite make
sense). There have been attempts to also add a proper bag/multiset
type, but the use cases for bags are relatively few and
collections.Counter is usually close enough that it can be used in
such cases, although not as elegantly.


More information about the Python-ideas mailing list