Since nobody's mentioned it yet here's a zip() solution:
>>> def chunker(iterable, chunksize): ... return zip(*[iter(iterable)]*chunksize) It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.
Example:
>>> s = '1234567890' >>> chunker(s, 3) [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')] >>> chunker(s, 4) [('1', '2', '3', '4'), ('5', '6', '7', '8')] >>> chunker(s, 5) [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')] Or using itertools.izip to return an iterator instead of a list:
>>> from itertools import izip >>> def chunker(iterable, chunksize): ... return izip(*[iter(iterable)]*chunksize) Padding can be fixed using @ΤΖΩΤΖΙΟΥ's answer@ΤΖΩΤΖΙΟΥ's answer:
>>> from itertools import chain, izip, repeat >>> def chunker(iterable, chunksize, fillvalue=None): ... it = chain(iterable, repeat(fillvalue, chunksize-1)) ... args = [it] * chunksize ... return izip(*args)