Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Created October 10, 2011 14:08

Revisions

  1. ksamuel created this gist Oct 10, 2011.
    12 changes: 12 additions & 0 deletions chunk_iterable.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    from itertools import chain, islice

    def chunk(seq, chunksize, process=iter):
    """ Yields items from an iterator in iterable chunks."""
    it = iter(seq)
    while True:
    yield process(chain([it.next()], islice(it, chunksize - 1)))

    if __name__ == '__main__':
    lst = ['a', 'b', 'c', 'd', 'e', 'f']
    for i in chunk(lst, 2, list):
    print i