def chunks iterable length fill False filler None drop_incomplete True

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def chunks(iterable, length=2, fill=False, filler=None, drop_incomplete=True):
"""Iterate through iterable in chunks"""
iterable = iter(iterable)
while True:
data = tuple(itertools.islice(iterable, length))
if len(data) == length:
yield data
else:
if fill:
data += tuple(filler for _ in xrange(length - len(data)))
yield data
elif not drop_incomplete:
yield data
return