Python filter() Function is used to get filtered elements. Python filter() Function takes two arguments, first is a function and the second is iterable.
Python filter() Function returns a sequence from those elements of iterable for which function returns True.
The first argument can be None if the function is not available and returns only elements that are True.
- filter (function, iterable)
function: It is a function. If set to None returns only elements that are True.
Iterable: Any iterable sequence like list, tuple, and string.
Both the parameters are required.
It returns the same as returned by the function.
Let’s see some examples of filter() function to understand it’s functionality.
It is normally used with Lambda functions to separate list, tuple, or sets.
|# a list contains both even and odd numbers.
seq = [0, 1, 2, 3, 5, 8, 13]
# result contains odd numbers of the list
result = filter(lambda x: x % 2 != 0, seq)
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
[1, 3, 5, 13]
[0, 2, 8]
|# Python filter() function example
# Calling function
result = filter(mulof3,(1,3,5,6,8,9,12,14))
# Displaying result
result = list(result)
print(result) # multiples of 3
[3, 6, 9, 12]