How to Split a List in Python According to a Condition?

Estimated read time 2 min read

To split a list in Python according to a condition, you can use the groupby() function from the itertools module. The groupby() function takes an iterable and a key function, and groups the elements of the iterable based on the return value of the key function.

Here’s an example of how you might split a list in Python according to a condition using groupby():

from itertools import groupby

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
groups = groupby(my_list, lambda x: x % 2 == 0)
even_numbers, odd_numbers = [], []
for is_even, group in groups:
    if is_even:
        even_numbers.extend(group)
    else:
        odd_numbers.extend(group)
print(even_numbers)
print(odd_numbers)

In this example, we define a list my_list with ten integers. We then use the groupby() function to group the elements of my_list based on whether they are even or odd. The lambda function lambda x: x % 2 == 0 is used as the key function to group the elements.

We then iterate over the groups returned by groupby(), and use a conditional statement to append the elements to either the even_numbers list or the odd_numbers list, depending on whether they are even or odd.

When run, this program will output the following:

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Note that the groupby() function requires that the input iterable be sorted by the key function. In this example, the elements of my_list are naturally sorted because the even elements come before the odd elements, but in other cases you may need to sort the list explicitly before using groupby().

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply