The itertools module documentation. Read it, learn it, love it.
Specifically, from the recipes section:
import itertools
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
Which gives:
>>> tuple(grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5, None))
which isn't quite what you want...you don't want the None
in there...so. a quick fix:
>>> tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))
If you don't like typing the list comprehension every time, we can move its logic into the function:
def my_grouper(n, iterable):
"my_grouper(3, 'ABCDEFG') --> ABC DEF G"
args = [iter(iterable)] * n
return tuple(tuple(n for n in t if n)
for t in itertools.izip_longest(*args))
Which gives:
>>> tuple(my_grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))
Done.