Welcome, guest | Sign In | My Account | Store | Cart

Groups the elements returned by an iterator into n-tuples. The final tuple may be padded with Nones.

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from itertools import *
def group(lst, n):
    """group([0,3,4,10,2,3], 2) => iterator
    
    Group an iterable into an n-tuples iterable. Incomplete tuples
    are padded with Nones e.g.
    
    >>> list(group(range(10), 3))
    [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
    """
    iters = tee(lst, n)
    iters = [iters[0]] + [chain(iter, repeat(None))  
                 for iter in iters[1:]]
    return izip(
         *[islice(iter, i, None, n) for i, iter 
              in enumerate(iters)])

1 comment

Jim Baker 17 years, 8 months ago  # | flag

Also see itertools recipes (5.16.3 in Python 2.4.3 documentation). This is a useful function that probably many of us have implemented in a number of different ways. But I like the conciseness of the "standard" version of the recipe:

from itertools import chain, repeat, izip
def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)