The filter() method filters the given iterable with the help of a function that tests each item in the iterable to be true or not. Python filter() method constructs the iterator from items of an iterable for which a function returns true.
Python filter() is an inbuilt function that returns an iterator where the items are filtered through a function to test if the item is accepted or not.
filter(function, iterable)
filter() Parameters
The function takes two parameters:
filter() Return Value
filter()
function returns an iterator.letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if letter in vowels:
return True
else:
return False
# selects only vowel elements
filtered_vowels = filter(filter_vowels, letters)
# converting to tuple
vowels = tuple(filtered_vowels)
print(vowels)
Output:
('a', 'e', 'i', 'o')
Here's how the above program works :
letters
is passed to the filter_vowels()
functionfilter_vowels()
returns True
, filter() selects the elementNote: Here, the program returns the iterator, which we converted into a tuple using the vowels = tuple(fitered_vowels)
.
Thanks for reading !!!
#python #python filter