Python filter() function is used to filter the elements of an iterable based on a function. This function returns filter
object that is an iterator.
Python filter()
Python filter() function syntax is:
1 2 3 |
filter(function, iterable) |
function
will be called on iterable
elements and if it returns True
then they will be part of the returned iterator.
We can also pass the function as None
, in that case, standard truth testing rules will be followed to determine if the iterable elements are True or False. You can get more details about them in Python bool example.
Python filter() example
Let’s define a function to check if the input number is even or not. It will return True if the number is even, else False.
We will also define a utility function to print elements of the iterator.
1 2 3 4 5 6 7 8 9 10 11 |
def is_even(x): if x % 2 == 0: return True else: return False def print_filter_items(my_filter): for item in my_filter: print(item, end=' ') print() |
Let’s use filter() function to get an iterator of even numbers only from the input iterable of integers. We will use tuple and list for our example, both of them are iterable.
1 2 3 4 5 6 7 8 9 |
l1 = [1, 2, 3, 4, 5] fl = filter(is_even, l1) print(type(fl)) print_filter_items(fl) t = (1, 2, 3, 4, 5) fl = filter(is_even, t) print_filter_items(fl) |
Output:
1 2 3 4 5 |
<class 'filter'> 2 4 2 4 |
Python filter() example with None function
1 2 3 4 5 |
t = (True, False, 1, 0, 0.0, 0.5, '', 'A', None) fl = filter(None, t) print_filter_items(fl) |
Output:
1 2 3 |
True 1 0.5 A |
Notice that zero, empty string, False and None are filtered out because their boolean value is False.
Reference: Official Documentation