Skip to content

Instantly share code, notes, and snippets.

@tiwijo
Created October 12, 2011 19:37
Show Gist options
  • Save tiwijo/1282290 to your computer and use it in GitHub Desktop.
Save tiwijo/1282290 to your computer and use it in GitHub Desktop.
Chunking n adjacent items in a list
#! /usr/bin/env python
from itertools import izip_longest
def ichunk(iterable, n):
'''Chunk n adjacent elements in the iterable. For example
ichunk((1,2,3,4,5,6), 2) -> (1,2),(3,4),(5,6)'''
iters = (iter(iterable),) * n
return izip_longest(*iters, fillvalue=None)
if '__main__' == __name__:
x = range(20)
for i in range (1, 21):
print list(ichunk(x, i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment