Python filter() function allows us to extract some elements from an iterable by condition. In this tutorial, we will use some examples to show you how to do.
Syntax
Python filter() is defined as:
filter(function, iterable)
If function receives an element in iterable and returns True, this element will be extracted.
How to use python filter()?
Here is an example.
x = [1, 2, 3, 4, 5] def is_true(x): if x%2 == 0: return True return False y = filter(is_true, x) print(y) for e in y: print(e)
Run this code, we will get:
<filter object at 0x0000025E54F91BE0> 2 4
We can find filter() will return a filter object.
In this example, 2, 4 will return True in is_true() function.
Generally, we often use this function with lambda function.
Understand Python Lambda Function for Beginners – Python Tutorial
x = [1, 2, 3, 4, 5] y = filter(lambda x: x%2 == 0, x) print(y) for e in y: print(e)
Run this code, we will get:
<filter object at 0x00000255D4B8C518> 2 4