Linux How To's | Bash Scripting | Python

Thursday, 29 December 2016

Python filter() Function - We have been learning some of the important utilities used in function programming that includes functions – map(), reduce() and filter(). We have already covered map() function and reduce() in our recent articles. In this article, we will learn about filter() function. Let’s begin with the discussion straight away.

Using reduce() with lambdas

As the name suggests, filter() function filters out some elements from a sequence. Just like map() and reduce() functions, this function receives two arguments – a function and an iterable object. The function is usually called as filter and returns either True or False. This function is then executed on each element of the iterable. As a result, we get a list of items for which the filter returns True.

Don’t be afraid, if its difficult to understand, we will see some examples and explain them in details. To begin with, we try to extract even number from a list of numbers. We need to create the filter, at first. We can use a normal function or a lambda, but it should return either True or False only, nothing else.

In the above examples, we have a function that returns True if a number is even, False otherwise. So, it will start iterating through the iterable, and pass the item to the function as an argument. If for a particular item, function returns True, it is added to the output list, otherwise skipped. In the end, we get a list of all those items for which function has retuned True. If we were to write an equivalent code to have the same behavior, code would have looked like -

With this, we close our discussion on filter() function. It was pretty straight forward to understand and use. We just need a

filter - a function which returns Boolean values and an iterable. As a result, we get a list with items for which filter returned True. Please share your views and feedback in the comments section below and stay tuned for more articles. Thank you.