Tutorial Study Image

Python filter()

The filter() function is used for returning an iterator, here the elements are filtered through the function.it helps to test each element in the sequence to be true or not.


filter(function, iterable) #Where iterable can be a list, string, tuple, dictionary , set etc 

filter() Parameters:

It takes functions and iterable as parameters.

Parameter Description Required / Optional
function A function that tests if the element is accepted or not Required
iterable  Iterable may be a set, lists, tuples, etc... Required

filter() Return Value
 

Input Return Value
iterable(if element) iterator(filtered list)
iterable(if not element) False

Examples of filter() method in Python

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)
 

Output:

The filtered vowels are:
a
e
i
o

Example 2: How filter() works using a pre-defined function?


# Returns the elements which are multiples of 5
def multipleOf5(n):
  if(n % 5 == 0):
    return n
myList = [10, 25, 17, 9, 30, -5]
myList2 = list(filter(multipleOf5, myList))
print(myList2)
 

Output:

[10, 25, 30, -5]

Example 3: 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)
 

Output:

The filtered elements are:
1
a
True
0