Python filter() Method Tutorial

Python provides the List, Tuple, Dictionary, Set data types in order to store sequences. Python also provides the filter() method in order to test each element or item in a sequence to test for the given condition and return True or False according to the test result.

filter() Method Syntax

The filter() method has the following syntax.

filter( FUNCTION , SEQUENCE )
  • FUNCTION is the function which will test each item or element for the given SEQUENCE and return True or False.
  • SEQUENCE is the sequence type like List, Dictionary, Tuple which will be tested with the given FUNCTION.

Filter List

The list is the most popular sequential data type used in Python. The filter() method mostly used for a list of data types in order to filter the items of the list. In the following example, we will filter the even numbers from the odd numbers by using the function named even() . Keep in mind that the filer() method will return an iterable object which will provide given items when iterated with for.

mylist = [ 2 , 5 , 4 , 6 , 8 , 1 , 0 ]

def odd(number):
   if ( number in [ 1 , 3 , 5 , 7 , 9 ] ):
      return True
   else:
      return False

odd_numbers= filter ( odd , mylist )

for number in odd_numbers:
   print( number )

filter() Method with Lambda Function

Alternatively, the filter() method can be used with a lambda function. The lambda function will be written into the filter() method without creating a function with def etc.

mylist = [ 2 , 5 , 4 , 6 , 8 , 1 , 0 ]

odd_numbers= filter( lambda number: number in [ 1 , 3 , 5 , 7 , 9 ] , mylist )

for number in odd_numbers:
   print( number )

Leave a Comment