(Last Updated On: 17/02/2023)
Python Program to Split a List Into Evenly Sized Chunks Using Collections
# Split a List Into Evenly Sized Chunks in Python Using Collections
from collections import deque
def split_list(input_list, chunk_size):
# Create a deque object from the input list
deque_obj = deque(input_list)
# While the deque object is not empty
while deque_obj:
# Pop chunk_size elements from the left side of the deque object
# and append them to the chunk list
chunk = []
for _ in range(chunk_size):
if deque_obj:
chunk.append(deque_obj.popleft())
# Yield the chunk
yield chunk
input_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
chunk_size = 3
chunks = list(split_list(input_list, chunk_size))
print(chunks)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]