Python filter()

The filter() method constructs an iterator from elements of an iterable for which a function returns true.

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(function, iterable)

filter() Parameters

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 filterVowels(letter):
    vowels = ['a', 'e', 'i', 'o', 'u']

    if(letter in vowels):
        return True
    else:
        return False

filteredVowels = filter(filterVowels, letters)

print('The filtered vowels are:')
for vowel in filteredVowels:
    print(vowel)

Output

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 filter() method.

We have a function filterVowels 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 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 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
randomList = [1, 'a', 0, False, True, '0']

filteredList = filter(None, randomList)

print('The filtered elements are:')
for element in filteredList:
    print(element)

Output

The filtered elements are:
1
a
True
0

Here, we have a random list of numbers, 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).