[issue1643] Add group() to itertools

Kirk McDonald report at bugs.python.org
Tue Dec 18 02:49:19 CET 2007


New submission from Kirk McDonald:

One question which is asked with surprising frequency in #python is how
to yield multiple objects at a time from an iterable object. That is,
given [1, 2, 3, 4, 5, 6], get [(1, 2), (3, 4), (5, 6)]. 

The "grouper" function in the itertools recipes page provides one
pattern for this. A similar function (which behaves differently when the
length of the iterable is not evenly divisible by n) looks like this:

def group(iterable, n=2):
    return itertools.izip(*(iter(iterable),)*n)

This code is fairly opaque to the novice. It is ugly, and takes a bit of
head-scratching to realize exactly what it is doing. Because this
operation is asked for with some frequency, and because this general
implementation is so ugly, I believe it belongs in the library.

There is a related function which is asked for much less frequently, but
which is a more general case of the group() function listed above. This
other function has a third "step" argument. This argument controls how
far each group is in advance of the previous group. For example:

list(group([1, 2, 3, 4], n=2, step=1)) -> [(1, 2), (2, 3), (3, 4)]

The original function is equivalent to this function when step is equal
to n.

Please find attached a patch with implementation, documentation, and tests.

----------
components: Library (Lib)
files: itertools.group.patch
messages: 58716
nosy: KirkMcDonald
severity: normal
status: open
title: Add group() to itertools
versions: Python 2.6
Added file: http://bugs.python.org/file8979/itertools.group.patch

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue1643>
__________________________________
-------------- next part --------------
A non-text attachment was scrubbed...
Name: itertools.group.patch
Type: application/octet-stream
Size: 8427 bytes
Desc: not available
Url : http://mail.python.org/pipermail/python-bugs-list/attachments/20071218/bd4b3467/attachment.obj 


More information about the Python-bugs-list mailing list