This post will discuss how to conditionally split a list in Python.

1. Using List Comprehension

A simple and Pythonic solution to split a list in Python is to use the list comprehension. It creates a new list from existing ones by applying some expression or condition to each element. For example, the following code iterates over the elements of a list and check if they are even or odd, and creates two new lists with the elements matching the condition.

Download  Run Code

 
This method is easy to use and works for any condition that can be expressed as a boolean expression. However, it may not be very efficient if we have a large list as we have to loop through the list twice to split it.

2. Using filter() function

Another way to split a Python list is to use the built-in filter() function. This function takes two arguments: a function and an iterable object, and returns an iterator that contains only the elements of the iterable object for which the function returns True. Here is an example:

Download  Run Code

 
In the above example, we have defined a custom function that checks if an integer is even. Then, filter() function apply this function to each element of the list and convert the iterator to a list using the list() constructor. For the odd numbers, a lambda function is used that negates the result of the is_even() function.

3. Using for-loop

Finally, we can efficiently replace both list comprehensions with a single for-loop and an if-else statement. Here’s what the code would look like:

Download  Run Code

That’s all about conditionally split a list in Python.