[Python-ideas] itertools.chunks(iterable, size, fill=None)

MRAB python at mrabarnett.plus.com
Sat Sep 1 21:02:20 CEST 2012


On 01/09/2012 18:16, Michele Lacchia wrote:
> + 1 for the lazy version. Why not using itertools.islice instead of the
> innermost for loop?
>
OK, here's a lazy version using islice:


from itertools import islice

def chunks(seq, size):
     '''Cut sequence into chunks of given size. If `seq` length is
        not divisible by `size` without reminder, last chunk will
        have length less than size.

        >>> list( chunks([1,2,3,4,5,6,7], 3) )
        [[1, 2, 3], [4, 5, 6], [7]]
     '''
     if size < 1:
         raise ValueError("chunk size less than 1")

     it = iter(seq)

     while True:
         chunk = list(islice(it, 0, size))
         if not chunk:
             break

         yield chunk




More information about the Python-ideas mailing list