4

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.

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

6 Comments

Geez, thank you! I tried to write something like this, but I missed not placing the (x) after the function
Of course! Stackoverflow says that I have to wait 7min, but I'll do that. just another thing. What if I have 2 functions? like f1 = lambda x:x>=5 and try to place f1 and check_odd inside the filter? Doesnt work using l2 = list(filter((f1 and check_odd), l1)) iwth or without (x)
The answer worked for you not because I added x only, it's because I transformed the funciton check_odd inside the lambda. You can use the lambda to wrap all your other condition checking functions. I'll update the answer to elaborate further.
Yeah, I realized that. I was just wondering if I could use 2 independent functions without having to creat another one to wrap both nor modify one of them to include the other
Well, in that case you should chain the filter calls one after the other (exactly like you did), however keep in mind that that is creating a separate list for each filter call, and that you can only chain and operator using this approach.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.