Methods and Functions

Python filter()

Python filter function is used to filter the given sequence by checking if each element is true or not. The true elements are presented and the elements that are false or not do pass the condition given are discarded with the help of this function.

python filter, python filter list

Syntax of Python filter

filter(function, iterable)

filter Python Parameters

The fitter() in python takes two parameters as the input. These are mentioned below:

Function The function parameter is used to test whether the elements of the iterable are true or false. If there are no elements, then the identity function is returned. This will be false if any of the elements are false.  
Iterable Filterable iterables include sets, lists, tuples, and containers of any iterators. 

Return value from filter()

For each element in the iterable, the filter() method returns an iterator that has passed the function check.

Example 1: How python filter list works for an iterable list?

In the example given below, we have provided a list of letters and we need to filter out those letters such that only the vowels are presented. Generally, this process is carried out using the for loop and passing the letters through the loop, but in python, with the help of the filter(), this process is carried out much faster and easier. 

In the below program we have defined a method filter(), this method 

Source Code:

                    

# 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() method works without the python filter function?

In the example given below, we have a list of letters and we need to present the vowels from the given list. 

For this, we can use the for loop. The for loop is used to pass each vowel through the loop and store the elements in another list. This is the traditional way to filter out the elements present in the list, but with the filter() present in Python the task is done much easier. 

Source Code:

                    

# 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

FAQs on Python Filter

Q1. What is a filter in Python?

Python filter is a built-in function that is used to filter the unwanted element from the given list. 

Q2. How do you filter in Python?

Elements can be filtered in python using the built-in filter(). Here is an example:

                    

age01 = [5, 12, 17, 18, 24, 32, 6, 8, 13]



def myFunction(a):

  if a < 18:

    return False

  else:

    return True



adult_age = filter(myFunction, age01)



for a in adult_age:

  print(a)



Output

18

24

32

Q3. How do you filter a list of objects in Python?

The filter(function, iterable) function takes a function as an argument and returns a Boolean value indicating whether this list entry should pass the filter. All elements that pass are returned as a new iterable object by the filter (a filter object).

Look at the program given below:

                    

list1 = ["Python", "CSharp", "Java", "Go"]

list2 = ["Python", "Scala", "JavaScript", "Go", "PHP", "CSharp"]



# function that filters duplicate string

def filterDuplicate(string_to_check):



    if(string_to_check in ll):

        return False

    else:

        return True



# Demonstrating filter() to remove duplicate strings

ll = list2

out_filter = list(filter(filterDuplicate, list1))

ll = list1

out_filter += list(filter(filterDuplicate, list2))



print("The new filtered list is: ", out_filter)



Output:


The new filtered list is: ['Java', 'Scala', 'JavaScript', 'PHP']

We can also use the lambda function to implement the filter() in python. In Python, the filter() method accepts two arguments: a function and a list. Using the lambda function is an approach to filter out all the elements of a sequence that the function returns ‘True’.

Q.4 How do you filter a string in Python?

                    
arr1 = ['p','y','t','h','o','n',' ','3','.','0']

arr2 = ['p','y','d','e','v',' ','2','.','0']



def interSection(arr1, arr2): # find identical elements



   #Filter() is used in a lambda 

#expression to find common values

   out = list(filter(lambda it: it in arr1, arr2))

   return out



# Main program

if __name__ == "__main__":

   out = interSection(arr1, arr2)

   print("Filtered seq. is as follows: ", out)



Output:

Filtered seq. is as follows: ['p', 'y', ' ', '.', '0']


                

In python, if you want to remove certain unwanted words from a string this can be possible by using the filter(). 

For example:

If you want to remove certain stop words from a sentence the words can be removed by using the filter():

List.of.the.stop.words=[” a”, “of”, “the”, “end”, “why”]

String:

“This is the beginning of the end of the world peace.”

Filtered string:

“This is beginning world peace.” 

Look at the program given below to understand how to carry out the process using the filter().

Source Code

                    
# List of the stop words we want to filter out

list_of_stop_words11 = [" a", "of", "the", "end", "why"]



# Original string passed in the program is:

string_to_process11 = "This is the beginning of the end of the world peace."



# Lambda expression that filters stop words

split_str1 = string_to_process11.split()

filtered_str1 = ' '.join((filter(lambda s: s not in list_of_stop_words11, split_str)))



print("The filtered string is: ", filtered_str1)

Output:

The filtered string is:

"This is beginning world peace."


                
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.