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() function syntax is:
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.
Copydef 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()
Copyl1 = [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)
Copy<class 'filter'> 2 4 2 4
Python filter() example with None function
Copyt = (True, False, 1, 0, 0.0, 0.5, '', 'A', None) fl = filter(None, t) print_filter_items(fl)
CopyTrue 1 0.5 A
Notice that zero, empty string, False and None are filtered out because their boolean value is False.
Reference: Official Documentation