To split a list in half using Python, the easiest way is with list slicing.

list_of_numbers = [0, 1, 2, 3, 4, 5]

first_half = list_of_numbers[:3]
second_half = list_of_numbers[3:]

print(first_half)
print(second_half)

#Output:
[0, 1, 2]
[3, 4, 5]

You can easily create a function which will find the middle position of a given list and split a list in half in Python.

def split_list_in_half(lst):
    middle = len(lst) // 2
    return [lst[:middle],lst[middle:]]

list_of_numbers = [0, 1, 2, 3, 4, 5, 6, 7]

print(split_list_in_half(list_of_numbers))

#Output:
[[0, 1, 2, 3], [4, 5, 6, 7]]

When working with lists in Python, the ability to manipulate them and create new lists is very valuable.

One such manipulation is the ability to split a list into half using Python.

To split a list in half, we just need to know the length of the list and then we can divide by two to get the middle position of the list.

Then to split a list in half, we can use list slicing.

Below is a simple function which will split a list in half for you in Python. Note: we use integer division so that we can use an integer for our slice.

def split_list_in_half(lst):
    middle = len(lst) // 2
    return [lst[:middle],lst[middle:]]

list_of_numbers = [0, 1, 2, 3, 4, 5, 6, 7]

print(split_list_in_half(list_of_numbers))

#Output:
[[0, 1, 2, 3], [4, 5, 6, 7]]

How to Split a List into Equal Sublists Using Python

If you want to split a list into more than two equal pieces, for example, to split a list into thirds, we can generalize our solution from above.

In Python, we can split a list into n sublists a number of different ways.

Given a length, or lengths, of the sublists, we can use a loop, or list comprehension to split a list into n sublists.

To split a list into n sublists, first we need to calculate the length of each sublist. While it might not always work out that there are equal lengths for all n sublists, we can get pretty close.

After getting the length of each sublist, we can then loop over the list and create a list of lists with slicing.

Below is a Python function which will split a list into n sublists with a for loop.

list_of_numbers = [0,1,2,3,4,5]

def getSublists(lst,n):
    subListLength = len(lst) // n
    list_of_sublists = []
    for i in range(0, len(lst), subListLength):
        list_of_sublists.append(lst[i:i+subListLength])
    return list_of_sublists

print(getSublists(list_of_numbers, 3))

#Output:
[[0, 1], [2, 3], [4, 5]]

Hopefully this article has been useful for you to learn how to split a list in half using Python.

Categorized in:

Python,

Last Update: March 12, 2024