BESS
BESS

Reputation: 71

Python - Filter function with multiple conditions

I know this is a dummy question, but I didn't find the answer here the way I had in mind

I just want to know if I can apply multiple filters within a single filter function

A simple code to try it:

def check_odd(x):

    return (x % 2) == 0

l1 = list(range(1,20))
list(filter((check_odd and lambda x:x>=5), l1))

Using the code above only one of the filters is applied (the 2nd).

I solved it using:

list(filter(check_odd, filter(lambda x:x>=5, l1)))

But I wonder if there is a way to group all filters in filter function.

Upvotes: 4

Views: 6070

Answers (1)

Maaddy
Maaddy

Reputation: 628

Just transform the and inside the lamda, and combine your conditions there:

def check_odd(x):
    return (x % 2) == 0

l1 = list(range(1,20))
l2 = list(filter((lambda x:x>=5 and check_odd(x)), l1))
print(l2)

Update
You can actually combine any number of conditions from other functions by wrapping them all inside the lambda. Here's an example:

def check_odd(x):
    return (x % 2) == 0

def check_greater_than_five(x):
    return x >= 5

def check_divisible_by_three(x):
    return x % 3 == 0

l1 = list(range(1,20))
l2 = list(filter((lambda x: (check_odd(x) or check_divisible_by_three(x)) and check_greater_than_five(x)), l1))
print(l2)   #prints all numbers that are greater than five, and are divisible by either 2 or 3

Upvotes: 8

Related Questions