In this post, we will learn how to split a list into multiple lists of N chunks in Python.
A List is one of the in-built data types in Python. It is used to store multiple elements in a single variable.
my_list = ['a','b','c']
Now, to split a list into multiple sublists in Python, we have to :
- First, find the length of the list
- Divide the list by 2, to get the middle index
- Use the middle index to divide the list into chunks of equal items.
Let’s split a number list using the above steps.
Split List into Multiple lists in Python
my_list = [1,2,3,4,5,6] length = len(my_list) mid_index = length // 2 first_chunk = my_list[:mid_index] second_chunk = my_list[mid_index:] print(first_chunk) print(second_chunk)
The output is:
[1, 2, 3] [4, 5, 6]
In the above example, we have used the
len() to get the length of the list.
Then to get the middle index we have divided the length by 2 like this
length // 2. We find the
mid_index as 3.
Next, to get the first chunk, we used
my_list[:mid_index]. It means get the items from
my_list starting from index 0 up to the mid_index (excluding the item in index 3).
Similarly to get the other half of the list we used
my_list[mid_index:], which means get the items from index 3 (
mid_index) up to the last index.
We can also use the Python library numpy to split a list into n parts.
Split a List into N parts using Numpy
To split a list into N parts of equal length, we can use the
numpy.array_split() function in numpy modules.
numpy is a Python library that helps us to work with arrays and have a collection of high-level mathematical functions.
Read more about it here: Numpy Documentation
So to divide a list into N parts of sublists we first import numpy and then use the
arr– it’s the list to be split.
section: section we want the list to be divided.
import numpy as np my_list = [1,2,3,4,5,6] split_part = np.array_split(my_list, 2) print(split_part)
The output is:
It returns a list with sublists of the equally parted list items.
In the above example, we have split the given list into two parts using
If you change the section argument to 3, it will split the list into three parts like this
split_part = np.array_split(my_list, 3) print(split_part)