[Python-Dev] "groupby" iterator

Guido van Rossum guido at python.org
Sun Nov 30 11:50:41 EST 2003

I lost David Eppstein's post, but I finally know what I want to say in
response.  David objected to the behavior of the groupby()
subiterators to become invalidated when the outer iterator is moved on
to the next subiterator.  But I don't think there's a good use case
for what he wants to do instead: save enough state so that the
subiterators can be used in arbitrary order.  An application
that saves the subiterators for later will end up saving a copy of
everything, so it might as well be written so explicitly, e.g.:

  store = {}
  for key, group in groupby(keyfunc, iterable):
      store[key] = list(group)
  # now access the groups in random order:
  for key in store:
      print store[key]

I don't think the implementation should be complexified to allow
leaving out the explicit list() call in the first loop.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list