My Coding > Programming language > Python > Python FAQ > Python: How to split list based on item condition

Python: How to split list based on item condition

Using condition function

As an example, let's split the list of integers list(range(10)) into even and odd lists. The condition will be very simple item % 2.


def condition(f):
    return f % 2

def split_on_condition(seq, condition):
    a, b = [], []
    for item in seq:
        (a if condition(item) else b).append(item)
    return a, b

data = list(range(10))
odd,even = split_on_condition(data, condition)

print('odd  = ', odd)  # odd  =  [1, 3, 5, 7, 9]
print('even = ', even) # even =  [0, 2, 4, 6, 8]

To make this less universal, jsut in the code, you can use the same but slightly more simple. But it is nesessary to undestand, that [x % 2] is a slice for list (even, odd) and it is nesessary to be very careful with values go to this slice. False can be used as 0 and True can be used as 1 in this slice respectively


data = list(range(10))
even, odd = [], []

for x in data:
    (even, odd)[x % 2].append(x)

print('odd  = ', odd)  # odd  =  [1, 3, 5, 7, 9]
print('even = ', even) # even =  [0, 2, 4, 6, 8]


Published: 2021-11-06 22:30:51

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.