If you know that you have a cut sequence (list or tuple),
def getrows_byslice(seq, rowlen): for start in xrange(0, len(seq), rowlen): yield seq[start:start+rowlen]
This, of course, is a generator, so if you absolutely need a list as a result, you will of course use list(getrows_byslice(seq, 3)) or the like.
If you start with a general iterable, itertools recipes offer help with a grouper recipe ...:
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)
(again, you will need to call list , if, of course, the list is what you want).
Since you really want the last tuple to be truncated rather than filled, you need to โtrimโ the final fill values โโfrom the most recent tuple.
Alex martelli
source share