Python - Filter Function
The filter()
function calls the specified function which returns boolen for each item of the specified iterable (list).
Syntax:
filter(function, iterable) --> filter object
Parameters:
- function: The function to be called for each element of the specified iterable.
- iterables: One or more iterables separated by a comma (such as string, list, tuple, dictionary).
Return Value:
Returns an iterator object of the filter
class.
The filter()
function also receives two arguments, a function and a sequence (e.g. a list).
Each item in the list is processed by the function which returns True
or False
. Only those items which return True
are stored in a filter object.
This can then be conveniently converted into a sequence.
The following function is_even()
returns True
if the passed number is an even number, otherwise it returns False
.
This function is used inside filter()
along with the list object.
def is_even(x):
if x%2 == 0:
return True
else:
return False
>>> numbers = [1, 2, 3, 4, 5]
>>> result = filter(is_even, numbers)
>>> next(result)
2
>>> next(result)
4
The lambda function can also be used in the filter()
function, as shown below.
>>> result = filter(lambda x: x%2==0, numbers)
>>> next(result)
2
>>> next(result)
4
You can specify None
as the function argument. In this case, the filter()
function will return all truthy values from an iterable, as shown below.
>>> mylist = [0, 1, 2, 3, False, True, 5]
>>> result = filter(None, mylist)
>>> list(result)
[1, 2, 3, True, 5]