In simple words,
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:
filter() method takes two parameters:
- function - function that tests if elements of an iterable return true or false
If None, the function defaults to Identity function - which returns false if any elements are false
- iterable - iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators
Return value from filter()
filter() method returns an iterator that passed the function check for each element in the iterable.
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)
Example 1: How filter() works for iterable list?
# list of letters letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] # function that filters vowels def filter_vowels(letter): vowels = ['a', 'e', 'i', 'o', 'u'] if(letter in vowels): return True else: return False filtered_vowels = filter(filter_vowels, letters) print('The filtered vowels are:') for vowel in filtered_vowels: print(vowel)
The filtered vowels are: a e i o
Here, we have a list of letters and need to filter out only the vowels in it.
We could use a for loop to loop through each element in letters list and store it in another list, but in Python, this process is easier and faster using
We have a function
filter_vowels that checks if a letter is a vowel or not. This function is passed onto
filter() method with the list of letters.
filter() method then passes each letter to the
filter_vowels() function to check if it returns true or not. In the end, it creates an iterator of the ones that return true (vowels).
Since the iterator doesn't store the values itself, we loop through it and print out vowels one by one.
Example 2: How filter() method works without the filter function?
# random list random_list = [1, 'a', 0, False, True, '0'] filtered_list = filter(None, random_list) print('The filtered elements are:') for element in filtered_list: print(element)
The filtered elements are: 1 a True 0
Here, we have a random list of numbers, string, and boolean in random_list.
We pass random_list 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 random_list is checked if it's true or not.
When we loop through the final filtered_list, we get the elements which are true:
1, a, True and '0' ('0' as a string is also true).