How to Split Python List to Evenly Sized Chunks?
Following Python program splits a list to evenly sized chunks. User defined unction even_chunks()
converts original_list
to different chunks of length size
.
Python Source Code: List to Evenly Sized Chunks
def even_chunks(original_list, size):
for i in range(0, len(original_list), size):
yield list(original_list[i:i + size])
test_list = range(45)
chunks = even_chunks(test_list, 5)
for chunk in chunks:
print(chunk)
Output
Output of the above program is:
[0, 1, 2, 3, 4] [5, 6, 7, 8, 9] [10, 11, 12, 13, 14] [15, 16, 17, 18, 19] [20, 21, 22, 23, 24] [25, 26, 27, 28, 29] [30, 31, 32, 33, 34] [35, 36, 37, 38, 39] [40, 41, 42, 43, 44]