Python - Filter Function
filter() function calls the specified function which returns boolen for each item of the specified iterable (list).
filter(function, iterable) --> filter object
- 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).
Returns an iterator object of 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
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
True if the passed number is an even number, otherwise it returns
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]