You can define a function that iterates over and collects the list
elements. When the given chunk-size is reached, the chunk is appended to a
result
list. Here is code that does this:
def chunks(l, chunk_size):
result = []
chunk = []
for item in l:
chunk.append(item)
if len(chunk) == chunk_size:
result.append(chunk)
chunk = []
# don't forget the remainder!
if chunk:
result.append(chunk)
return result
print(chunks([1, 2, 3, 4, 5], 2))
Running the code gives this output:
[[1, 2], [3, 4], [5]]
You can also use yield
to turn the function into a generator.