scotfl.ca

array_chunk in Python

def chunk(seq, chunk_size): “”"Split a sequence into chunks.

    >>> chunk(range(10),2)
    [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

    The final chunk may have fewer than chunk_size elements.
    >>> chunk(range(10),3)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    """
    return [
        seq[offset:offset+chunk_size]
        for offset in xrange(0, len(seq), chunk_size)
    ]

This entry was posted on 23 February 2008 at 19:37 and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

2 Responses to “array_chunk in Python”

  1. Nathan — February 23rd, 2008 at 22:30

    The recipes page for itertools has a function that does this and will pad the last group to the correct length. Second from the bottom http://docs.python.org/lib/itertools-recipes.html

  2. scotflFebruary 24th, 2008 at 01:52

    Excellent. I knew the functionality had to exist somewhere, but the PHP noise rendered my google searches useless.