Given:
>>> li [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
There is a common Python idiom that uses zip in combination with iter and * to split a list into a flat list into a list of lists of n lengths:
>>> n=3 >>> zip(*([iter(li)] * n)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14), (15, 16, 17), (18, 19, 20)]
However, if n not an even multiple of the total length, the final list is truncated:
>>> n=4 >>> zip(*([iter(li)] * n)) [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18, 19)]
You can use izip_longest to use the full list populated with the selected value for incomplete subscriptions:
>>> list(izip_longest(*([iter(li)] * n))) [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18, 19), (20, None, None, None)]