DEV Community

Free Python Code
Free Python Code

Posted on

Explain the filter function in Python

Hi 🙂🖐

The filter function returns an iterator where the items are filtered through a function to test if the item is accepted or not.

filter function take 2 parameters filter(function, iterable)

Imagine that you have a list of prices and you want to get only the prices < 150 and prices > 25.

my_list = [100, 150, 270, 25, 75, 370]
Enter fullscreen mode Exit fullscreen mode

Now you need to create a function to filter this prices.

def my_filter_func(num):
    if num < 150 and num > 25:
        return True
Enter fullscreen mode Exit fullscreen mode

Now you need to make a loop on all list

best_Prices = []
for num in my_list:
    if my_filter_func(num):
        best_Prices.append(num)

print(best_Prices) # [100, 75]
Enter fullscreen mode Exit fullscreen mode

This is how the filter function works. Now that we know how it works, we don't need to write all this code. Just use a filter.

best_Prices = filter(my_filter_func, my_list)
best_Prices = list(best_Prices)

print(best_Prices) ## [100, 75]
Enter fullscreen mode Exit fullscreen mode

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

Top comments (0)