In simple words, the filter() method filters the given iterable with the help of a function that tests each element in the iterable to be true or not.
The syntax of filter() method is:
The filter() method takes two parameters:
The filter() method returns an iterator that passed the function check for each element in the iterable.
The filter() method is equivalent to:
# when function is defined
(element for element in iterable if function(element))
# when function is None
(element for element in iterable if element)
# list of alphabets
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# function that filters vowels
vowels = ['a', 'e', 'i', 'o', 'u']
if(alphabet in vowels):
filteredVowels = filter(filterVowels, alphabets)
print('The filtered vowels are:')
for vowel in filteredVowels:
When you run the program, the output will be:
The filtered vowels are:
Here, we list have a list of alphabets and need to filter out only the vowels in it.
We could use a for loop to loop through each element in alphabets list and store it in another list, but in Python, this process is easier and faster using filter() method.
We have a function filterVowels that checks if an alphabet is a vowel or not. This function is passed onto the filter() method with the list of alphabets.
The filter() method then passes each alphabet to the filterVowels() method to check if it returns true or not. In the end, it creates an iterator of the ones that return true (vowels).
Since, iterator doesn't store the values itself, we loop through it and print out vowels one by one.
# random list
randomList = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomList)
print('The filtered elements are:')
for element in filteredList:
The filtered elements are:
Here, we have a random list of number, string and boolean in randomList.
We pass randomList to the filter() method with first parameter (filter function) as None.
With filter function as None, the function defaults to Identity function, and each element in randomList is checked if it's true or not.
When we loop through the final filteredList, we get the elements which are true: 1, a, True and '0' ('0' as a string is also true).
1, a, True and '0'