I have come up to following solution without creation temorary list object, which should work with any iterable object. Please note that this version for Python 2.x:
def chunked(iterable, size):
stop = []
it = iter(iterable)
def _next_chunk():
try:
for _ in xrange(size):
yield next(it)
except StopIteration:
stop.append(True)
return
while not stop:
yield _next_chunk()
for it in chunked(xrange(16), 4):
print list(it)
Output:
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[]
As you can see if len(iterable) % size == 0 then we have additional empty iterator object. But I do not think that it is big problem.