Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hello,
I'm trying to find a simpler way to do the following:
def list_split(list, size):
result = [[]]
while len(list) > 0:
if len(result[-1]) >= size: result.append([])
result[-1].append(list.pop(0))
return result
Example usage:
>>> list_split([0, 1, 2, 3, 4, 5, 6], 2)
[[0, 1], [2, 3], [4, 5], [6]]
>>> list_split([0, 1, 2, 3, 4, 5, 6], 3)
[[0, 1, 2], [3, 4, 5], [6]]
I can't tell if there's a built-in way to do this, possibly with slicing or something.
This is similar but not the same to the post at http://stackoverflow.com/questions/2235526/how-to-split-a-list-into-a-given-number-of-sub-lists-in-python-closed
Thanks
EDIT: As is commented on by Anurag Uniyal, this is a duplicate of http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python/312467#312467, and should be closed, which I cannot do.