def chunks iterable size longest True fillwith None iterable iter iter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def chunks(iterable, size, longest=True, fillwith=None):
iterable = iter(iterable)
while True:
ret = ()
try:
for x in xrange(size):
ret += (iterable.next(), )
except StopIteration:
if longest and ret:
while len(ret) < size:
ret += (fillwith, )
yield ret
return
yield ret