Split a list into evenly sized chunks in Python
You must be familiar with Python lists and their operations. Lists simply are a collection of data separated by commas and held within square brackets []. However, do you know how to split a list into equal-sized chunks? Well, in this tutorial, you will learn the same.
Different ways to split a list into evenly sized chunks
Method 1: Using Yield
You may be aware that on using yield, the function becomes a generator function. That is, the state of the function is preserved even if the execution is paused.
So, we make use of the same to loop through the entire list and keep returning evenly sized chunks.
def split(list, no_of_chunks): for i in range(0, len(list), no_of_chunks): yield list[i:i + no_of_chunks] no_of_chunks = 2 eg_list = [1,2,3,4,5,6,7,8,9,10] print(list(split(eg_list, no_of_chunks)))
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
In the above program, we have defined a function and used the for loop to iterate throughout the length of the list. Here, i+no_of_chunks returns an even number of chunks.
Method 2: Using List Compression to split a list
You can also do the same process discussed above in a simpler, shorter way as follows;
no_of_chunks = 2 eg_list = [1,2,3,4,5,6,7,8,9,10] res_list = [eg_list[i:i + no_of_chunks] for i in range(0, len(eg_list), no_of_chunks)] print(res_list)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
Method 3: Using NumPy
import numpy as np eg_list = [1,2,3,4,5,6,7,8,9,10] print(np.array_split(eg_list, 2))
You can use the numpy’s array_split()
method to split the array into a specified number of subarrays.
Syntax: numpy.array_split(array_name, no_of_chunks)
Method 4: Using Itertools
The zip_longest() method of python’s Itertools module loops throughout the specified iterables and prints their values. Any leftover value is filled by the value specified in the fillvalue parameter.
from itertools import zip_longest eg_list = [1,2,3,4,5,6,7,8,9,10] def split(no_of_chunks, iterable, padvalue='x'): return zip_longest(*[iter(iterable)]*no_of_chunks, fillvalue=padvalue) for output in split(2,eg_list): print(output)
(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)from itertools import zip_longest eg_list = [1,2,3,4,5,6,7,8,9,10,11] def split(no_of_chunks, iterable, padvalue='x'): return zip_longest(*[iter(iterable)]*no_of_chunks, fillvalue=padvalue) for output in split(2,eg_list): print(output)
(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)
(11, ‘x’)
Related articles you can refer to include,
Leave a Reply