Home >>Python Built-in Functions >Python filter() Function
Python filter() function is used to return an iterator were the given input items of the sequence are filtered through a function to test if the element in the sequence is accepted or not.
Syntax:filter(function, iterable)
Parameter | Description |
---|---|
function | This parameter defines a function to be run for each item in the iterable. |
iterable | This parameter defines the iterable to be filtered. |
ages = [15, 12, 16, 18, 20, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
name = ['a', 'b', 'h', 'i', 'm', 'a', 'n', 'y', 'u']
filtered = filter(fun, name)
print('The filtered letters are:')
for s in filtered:
print(s)