def chunked(seq, size, overflow=False): """ Chunk the sequence `seq` into chunks of `size`. It it's a string, return a sequence of strings. Otherwise, return a sequence of tuples. The returned object is a generator: >>> chunked("abcDEFghiJKL", 3) But for the sake of testing and example, we'll make lists: >>> list(chunked("abcDEFghiJKL", 3)) ['abc', 'DEF', 'ghi', 'JKL'] >>> list(chunked("abcDEFghiJKL", 9)) ['abcDEFghi'] >>> list(chunked("abcDEFghiJKL", 9, overflow=True)) ['abcDEFghi', 'JKL'] >>> list(chunked(range(15), 5)) [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14)] """ from itertools import izip, chain chunks = izip(*([iter(seq)] * size)) modulus = len(seq) % size if overflow and modulus: chunks = chain(chunks, [seq[-modulus:]]) if isinstance(seq, basestring): return (''.join(c) for c in chunks) else: return (tuple(c) for c in chunks)