[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:
http://mail.python.org/pipermail/python-ideas/2009-July/005219.html
http://www.mail-archive.com/python-list@python.org/msg229512.html

...the outcome of which was the Counter class:
http://docs.python.org/dev/py3k/library/collections.html#collections.Counter

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.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-ideas mailing list