for i in generate_chunks([1, 2, 3, 4, 5], 2):
print(i)
# [[1], [2, 3, 4, 5]]
# [[1, 2], [3, 4, 5]]
# [[1, 2, 3], [4, 5]]
# [[1, 2, 3, 4], [5]]
for i in generate_chunks([1, 2, 3, 4, 5], 3):
print(i)
# [[1], [2], [3, 4, 5]]
# [[1, 2], [3], [4, 5]]
# [[1, 2, 3], [4], [5]]
# [[1, 2], [3, 4], [5]]
# ...
How can I implement generate_chunks(list, n)
?
Essentially what generate_chunks
does is splitting list
in n
chunks and yield a list of these chunks.
For clarification, n
refers to the number of chunks, not the length of the chunks.
The order in which those lists of chunks are yielded is irrelevant, however the order of the elements in the initial list is important, so that for a given list [1, 2, 3]
the result [[1], [2, 3]]
would be valid whereas [[1], [3, 2]
would be invalid.
(Preferably without using a 3rd-party library)