I found the following code that is compatible with python2
from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
\"grouper(3, \'abcde
In Python 3's itertools
there is a function called zip_longest
. It should do the same as izip_longest
from Python 2.
Why the change in name? You might also notice that itertools.izip
is now gone in Python 3 - that's because in Python 3, the zip
built-in function now returns an iterator, whereas in Python 2 it returns a list. Since there's no need for the izip
function, it also makes sense to rename the _longest
variant for consistency.
According to the doc:
>>> s = [1,2,3,4,5,6,7,8,9]
>>> n = 3
>>> list(zip(*[iter(s)]*n))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
After all that discussion above, here's a python3 solution that I believe gives safer, more predicable results.
def chunker(iter, size):
chunks = [];
if size < 1:
raise ValueError('Chunk size must be greater than 0.')
for i in range(0, len(iter), size):
chunks.append(iter[i:(i+size)])
return chunks
example = [1,2,3,4,5,6,7,8,9]
print(' 1: ' + str(chunker(example, 1)))
print(' 3: ' + str(chunker(example, 3)))
print(' 4: ' + str(chunker(example, 4)))
print(' 8: ' + str(chunker(example, 8)))
print(' 9: ' + str(chunker(example, 9)))
print('10: ' + str(chunker(example, 10)))
The results are:
$ python3 iter_chunk.py
1: [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
3: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
4: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
8: [[1, 2, 3, 4, 5, 6, 7, 8], [9]]
9: [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
10: [[1, 2, 3, 4, 5, 6, 7, 8, 9]]