The filter() method constructs an iterator from elements of an iterable, based on whether an element can pass the test of a given function.
Example
#!/usr/bin/python3
def odd(x):
return x % 2 == 1
# Odd number judgment
tmp1 = filter(odd, [ 4, 5, 6, 7, 8, 9, 10,11,12,13,14])
tmp2 = list(tmp1)
print(tmp2)
Output:
[5, 7, 9, 11, 13]
Syntax
filter(function, iterable)
Parameters
Name | Description |
function | A function that tests if elements of an iterable return true or false |
iterable | Iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators |
Return Value
It returns an iterator that passed the function check for each element in the iterable.