How to Split a List into Equal Sized Chunks in Python?
A list in Python can hold a large number of elements. Sometimes you may need to split the elements of a list into equal sized chunks and then process. In this tutorial, we are going to learn how to divide the elements of a list into equal sized chunks in Python:
The following code example splits the given [3, 4, 9, 7, 1, 1, 2, 3] list into chunks, holding three elements each:
def to_chunks(list, chunk_size): result =  for i in range(0, len(list), chunk_size): result.append(list[i:i+chunk_size]) return result my_list = [3, 4, 9, 7, 1, 1, 2, 3] print(to_chunks(my_list, 3))
The output of the above code is:
[[3, 4, 9], [7, 1, 1], [2, 3]]