filter - a function which returns Boolean values and an iterable. As a result, we get a list with items for which filter returned
How it works
Python filter() Function - We have been learning some of the important utilities used in function programming that includes functions –
filter(). We have already covered
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
reduce()functions, this function receives two arguments – a function and an iterable object. The function is usually called as filter and returns either
False. This function is then executed on each element of the iterable. As a result, we get a
listof items for which the filter returns
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
Falseonly, nothing else.
How it works
In the above examples, we have a function that returns
Trueif a number is even,
Falseotherwise. 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 -
We take another simple example. In this, we will filter the non-negative numbers from a sequence of numbers. The logic to construct a filter is very simply and should be clear.
In the next example, we work on a list of strings, may be a list of names of continents, and filter out the ones who have less than 8 characters in them. Pretty simple, isn’t it?
With this, we close our discussion on
filter()function. It was pretty straight forward to understand and use. We just need a
True. Please share your views and feedback in the comments section below and stay tuned for more articles. Thank you.