Conditionally split a list in Python
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.
|
1 2 3 4 5 6 |
nums = list(range(10)) odd = [x for x in nums if x & 1] even = [x for x in nums if not x & 1] print(odd, even) # [1, 3, 5, 7, 9] [0, 2, 4, 6, 8] |
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:
|
1 2 3 4 5 6 7 8 9 |
def is_even(x): return 0 if x & 1 else 1 nums = list(range(10)) even = list(filter(is_even, nums)) odd = list(filter(lambda x: not is_even(x), nums)) print(odd, even) # [1, 3, 5, 7, 9] [0, 2, 4, 6, 8] |
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:
|
1 2 3 4 5 6 7 8 9 |
nums = list(range(10)) odd = [] even = [] for x in nums: (even if x & 1 else odd).append(x) print(odd, even) # [1, 3, 5, 7, 9] [0, 2, 4, 6, 8] |
That’s all about conditionally split a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)