I know this question has been covered many times but my requirement is different.
I have a list like: range(1, 26). I want to divide this list into a fi
This solution is based on the zip "grouper" pattern from the Python 3 docs. The small addition is that if N does not divide the list length evenly, all the extra items are placed into the first chunk.
import itertools
def segment_list(l, N):
chunk_size, remainder = divmod(len(l), N)
first, rest = l[:chunk_size + remainder], l[chunk_size + remainder:]
return itertools.chain([first], zip(*[iter(rest)] * chunk_size))
Example usage:
>>> my_list = list(range(10))
>>> segment_list(my_list, 2)
[[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
>>> segment_list(my_list, 3)
[[0, 1, 2, 3], (4, 5, 6), (7, 8, 9)]
>>>
The advantages of this solution are that it preserves the order of the original list, and is written in a functional style that lazily evaluates the list only once when called.
Note that because it returns an iterator, the result can only be consumed once. If you want the convenience of a non-lazy list, you can wrap the result in list:
>>> x = list(segment_list(my_list, 2))
>>> x
[[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
>>> x
[[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
>>>