Table of Contents
ToggleThe list is one of the important data structures in Python. A developer comes across a list on daily basis which makes it an essential data structure. The list has features like
- Can store different data types.
- It is mutable
- Ordered collection
- Can be of dynamic size
There are multiple ways of splitting a list in half using Python. You can choose any splitting method based on the complexity, time, and memory requirement.
Using Slicing to split a list in half
def split_list_into_halves(lst): mid = len(lst) // 2 return lst[:mid], lst[mid:] my_list = [1, 2, 3, 4, 5, 6, 7, 8] left_half, right_half = split_list_into_halves(my_list) print("Left half:", left_half) print("Right half:", right_half)output
Left half: [1, 2, 3, 4] Right half: [5, 6, 7, 8]‘lst[:mid]’ gives us the first half of the list and ‘lst[mid:]’ provides other half of the list.
Using loop for splitting the list in half
In this approach, we can split a list into multiple parts of equal size using a for loop. You can mention the parts variable value as 2 to split the list in half. However, you can apply any feasible value in the parts variable to split the list. This approach uses math module and list comprehension.
from math import ceil def split_list_into_parts(lst, parts=2): length = len(lst) part_size = ceil(length / parts) return [lst[i * part_size:(i + 1) * part_size] for i in range(parts)] # Example usage: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] parts = split_list_into_parts(my_list, parts=2) print("Parts:", parts)
output
Parts: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
Let’s grasp throught the code.
- Parts variable stores value for a number of parts you want to split the list into.
- Part_size calculates the size of each part
- We have used list comprehension “[lst[i * part_size:(i + 1) * part_size] for i in range(parts)]” . In this code line we iterate through the range of parts and slice the list accordingly. In the first go the code might seem little bit difficult to understand but list comprehension makes the code fast and readable.
Splitting the list into half using numpy
If you have the option of only using NumPy to split a list. You need to first install NumPy by executing following command “pip install numpy” in command prompt and then import the NumPy module in code.
import numpy as np def split_list_into_halves_np(lst): arr = np.array(lst) split_point = len(arr) // 2 return arr[:split_point].tolist(), arr[split_point:].tolist() my_list = [1, 2, 3, 4, 5, 6, 7, 8] left_half_np, right_half_np = split_list_into_halves_np(my_list) print("Left half (numpy):", left_half_np) print("Right half (numpy):", right_half_np) print("Parts:", parts)
output
Left half (numpy): [1, 2, 3, 4] Right half (numpy): [5, 6, 7, 8]
In the above code, we use np.array(lst) to convert the list into a numpy array. “Arr[split_point:]” and “arr[:split_point]” slice the numpy array to get the left and right halves.
We need to always choose the method that best fits our needs based on whether we prefer simplicity, efficiency or compatibility with other libraries we might be using.
Using itertools.islice for splitting a list into half.
If you don’t want to use numpy then we can follow itertool approach for splitting the list.
from itertools import islice def split_list_into_parts(lst, parts=2): length = len(lst) div, mod = divmod(length, parts) for i in range(parts): start = i * div + min(i, mod) end = (i + 1) * div + min(i + 1, mod) yield islice(lst, start, end) # Example usage: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] parts_iter = split_list_into_parts(my_list, parts=2) for part in parts_iter: print(list(part))
output
[1, 2, 3, 4, 5] [6, 7, 8, 9, 10]
In this approach:
- div variable calculates the size of each part. Mod variable handles the remainder when the list length is not perfectly divisible by parts.
- for i in range(parts): – Moves over the specified number of parts.
- start = i * div + min(i, mod) – Calculates the starting index for slicing the list. min(i, mod) ensures that the first mod parts get an extra element.
- end = (i + 1) * div + min(i + 1, mod) – Calculates the ending index for slicing the list.
- yield islice(lst, start, end) – Uses islice to slice the list lst from start to end and yields the resulting slice as a generator object.
- for part in parts_iter:
print(list(part)) - To print values in parts_iter variable. We loop over parts_iter and convert the part (generatot object) to list and print it
Using numpy.array_split to split the list into half
We have NumPy inbuilt function which helps to split the list into half. You have to first install NumPy by running the following command “pip install numpy” in the command prompt. Now let’s explore the code.
import numpy as np def split_list_into_approx_equal_parts(lst, parts=2): return np.array_split(lst, parts) my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] parts_np = split_list_into_approx_equal_parts(my_list, parts=2) print("Parts (numpy array_split):", parts_np)
output
Parts (numpy array_split): [array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10])]
The above numpy function np.array_split(lst,parts) takes two parameter i.e. a list which needs to be splitted and number of parts the list has to be splitted.
In the blog, we have seen 5 ways of how to spit a list in half python in a simple and efficient manner.