Last updated on December 2nd, 2022
There are many different ways to split a list into two parts. The code examples below demonstrate a few different methods: using a list comprehension, using a for loop, and using the filter() function.
Each method has its advantages and disadvantages, so it’s important to understand how each one works before deciding which one to use in a particular situation.
Let’s get into the detail of each method.
This website is supported by readers like you. If you purchase after clicking one of our affiliate links, we may earn a small commission at no extra cost to you.
List comprehension
This code will create a list of numbers from 1 to 5, then split that list into a list of sublists, where each sublist contains only one element from the original list. The resulting list will look like this: [[1], [2], [3], [4], [5]]
.
The range()
the function is used to create a list of indices that correspond to the elements in the original list, and the [i:i+1]
the syntax is used to extract each element from the original list as a separate sublist.
This code creates a list of numbers and then uses a for loop to iterate over the numbers and append them to either the even
or odd
list depending on whether they are even or odd. Finally, it prints the two sublists.
Using List Indexing Operator
The code below will split the original list my_list
into two halves: first_half
and second_half
. The first_half
will consist of the first three elements of my_list
(elements at index 0, 1, and 2), and second_half
will consist of the remaining elements of my_list
(elements at index 3, 4, and 5). When this code is run, it will print out the two halves of the list:
Built-in Function
The code below uses the filter()
function to split the original list my_list
into two parts: first_half
and second_half
. The filter()
the function takes a function and a list as arguments and returns a new list that contains only the elements from the original list for which the function returns True
.
In this case, the function that is passed to filter()
is a lambda function that returns True
for elements less than 3 and False
otherwise. This means that first_half
will contain only the elements from my_list
that is less than 3, while second_half
will contain only the elements from my_list
that is greater than 3.
Final Words
Now that you have seen a few different methods for splitting a list in Python, you can choose the one that best suits your need. List comprehension is often the most efficient way to do this, but be sure to consider all of your options before making your decision.
Please let me know if you see any errors in the code. As many of you probably know, I am just starting to learn Python (see also, ‘How to Transform Dictionary in Python?‘). Thanks in advance! Happy coding 🙂