How to Split Python List in Half
- Use the List Slicing to Split a List in Half in Python
-
Use the
islice()
Function to Split a List in Half Python -
Use the
accumulate()
Function to Split a List in Half in Python
Lists store elements at a particular index and are mutable, which means that we can later update the values in a list.
We will learn how to split a list in half in this tutorial.
Use the List Slicing to Split a List in Half in Python
List slicing grabs a specific portion of the list for some operation while the original list remains unaffected. That means it creates a duplicate of the list to perform the assigned task. The slicing operator ([:]
) in Python is used for this.
We split a list in half in the following code.
lst = ["a", "b", "c", "d", "e", "f"]
print(lst[:3])
print(lst[3:])
Output:
['a', 'b', 'c']
['d', 'e', 'f']
We can also create a function to split the list in half. We will use the len()
function to find the length of the list. We will half this value and use the list slicing method to split it in half.
For example,
def split_list(a_list):
half = len(a_list) // 2
return a_list[:half], a_list[half:]
A = ["a", "b", "c", "d", "e", "f"]
B, C = split_list(A)
print(B)
print(C)
Output:
['a', 'b', 'c']
['d', 'e', 'f']
We created a function split_list
that returns two halves of an existing list.
Note that it does not change the original list, as it creates a duplicate list to perform the assigned task.
Use the islice()
Function to Split a List in Half Python
In Python, itertools
is the inbuilt module allowing us to handle the iterators efficiently.
It makes the iteration through the iterables like lists and strings very easy. The islice
function is a part of the itertools
module. It selectively prints the values mentioned in its iterable container passed as an argument.
For example,
from itertools import islice
Input = ["a", "b", "c", "d", "e", "f"]
length_to_split = [len(Input) // 2] * 2
lst = iter(Input)
Output = [list(islice(lst, elem)) for elem in length_to_split]
print("Initial list:", Input)
print("After splitting", Output)
Output:
Initial list: ['a', 'b', 'c', 'd', 'e', 'f']
After splitting [['a', 'b', 'c'], ['d', 'e', 'f']]
Use the accumulate()
Function to Split a List in Half in Python
The zip()
function is used to combine elements from an iterable. We can use it with the accumulate()
function from the itertools
module to split a list in half.
For example,
from itertools import accumulate
Input = ["a", "b", "c", "d", "e", "f"]
length_to_split = [len(Input) // 2] * 2
Output = [
Input[x - y : x] for x, y in zip(accumulate(length_to_split), length_to_split)
]
print("Initial list :", Input)
print("After splitting", Output)
Output:
Initial list : ['a', 'b', 'c', 'd', 'e', 'f']
After splitting [['a', 'b', 'c'], ['d', 'e', 'f']]