Python filter()

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

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:

filter(function, iterable)

filter() Parameters

The filter() method takes two parameters:

  • function - function that tests if elements of an iterable returns 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()

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)

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
        return False

filteredVowels = filter(filterVowels, letters)

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

When you run the program, the output will be:

The filtered vowels are:

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 the filter() method with the list of letters.

The 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:

When you run the program, the output will be:

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).