Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Created October 10, 2011 14:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ksamuel/1275417 to your computer and use it in GitHub Desktop.
Save ksamuel/1275417 to your computer and use it in GitHub Desktop.
Function to iterate over an iterable chunk by chunk, choosing the number of item of each chunks and the type of the chunk
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment