In this tutorial we will learn about python filter method and its uses.
What is Python filter() Method?
The filter() method returns an iterator where the items are filtered through a method to test if the item is true or not.
The syntax of filter() method is:
Python filter() Method Parameters
filter() method takes two parameters:
- method – it will take a method that tests if elements of an iterable return true or false.
- iterable – iterable which will be filtered, can be sets, lists, tuples, or containers of any iterators
Let us see some examples of filter() method.
Example 1: How filter() method works for the iterable list?
# list of letters
letters = [‘a’, ‘b’, ‘d’, ‘e’, ‘i’, ‘j’, ‘o’]
# function that filters vowels
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
if(letter in vowels):
filtered_vowels = filter(filter_vowels, letters)
print(‘The filtered vowels are:’)
for vowel in filtered_vowels:
The output will be as follow:
The filtered vowels are:
Rules of filter() method
filter() method can take only an iterator as an input which can be passed in method to check for each element in the iterable.