Computer >> Computer tutorials >  >> Programming >> Python

What is filter() in python?


Through the filter method, we filter out specific elements of a list using a filter condition defined in a separate function. So we first create a user-defined function which will mention the criteria of filtering. Together this function and the supplied list will be taken as parameters to the filter function to give us the result.

Syntax

filter(filter_function, sequence)

Example

In the below example we create a function that will find the even numbers present in a list. Then it will discard them (return false). The remaining odd numbers will be added to the final list. We can modify this function to filter out numbers divisible by 3 or 5 or so.

num_list = [6,17, 32, 11, 21, 132]
def remove_even(x):
   if x%2 ==0 :
      return False
   else:
      return True
odd_nos = filter(remove_even, num_list)
for x in odd_nos:
   print(x)
   

Output

Running the above code gives us the following result −

17
11
21

Example

We can use the same approach to filter out vowels from a given list of alphabets. Here

letters = ['t','u','t','o','r','i','a','l','s']
def get_vowels(c):
   if c in ['a','e','i','o','o']:
      return True
   else:
      return False
vowel_list = filter(get_vowels, letters)
for w in vowel_list:
   print(w)

Output

Running the above code gives us the following result −

u
o
i
a