The Filter() method is one of the most useful and inbuilt method in Python programming language. The filter() method is an iterator which takes two parameter, function and iterable_objects.
The filter method filters elements from given iterable_objects if any element from that object doesn’t satisfy the condition defined inside given function or return false.
Filter method takes two parameters and it’s syntax is:
Two parameters are:
- function: this function takes one parameter, which will be an item from the given iterable object. and then checks the specific condition and returns true or false. If the item from that iterable satisfies the condition then it stores that item inside the filter object, otherwise it filters it.
- iterable_object: this iterable object could be any iterable e.g list, tuple, sets, etc. filter method will take each item from this iterable_object, and then it will pass it through the given function.
Now let’s try to understand this thing with an example to make it more clear
numbers = [1,2,3,4,5,6,7,8] def func(item): if item%2 == 0: return True filter_fun = filter(func, numbers) print(list(filter_fun))
In the above code, you can see we have a list called numbers. And we declared a func(item), which takes one parameter and then checks whether its even number or not. If its even number then return true.
then we performed filter method and inserted our declarer func and numbers(list) as arguments. Now this filter func will takes one item from given list(numbers) and then it will pass it through given func. If this item is an even no, then the func will return true and will store it inside filter object.
Now, this filter object is an iterator also. So, you can perform a loop or create a list from a filter object using the list() function.
Using Lambda expression with filter() method:
You can also use lambda expression instead of defining separate function to check condition:
def func(item): if item%2 == 0: return True Or lambda item:item%2==0
Now you can see that lambda expression makes it simpler and clearer. So, you can directly use this lambda expression inside.
That’s it in this article.
Read also: Map function in Python
So, I hope you all liked this article. If yes then please don’t forget to share this article with others. You can also subscribe to our blog via email to get future notifications from us.
Thanks to read…