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. The filter() method is also related to the map() and reduce() methods which are used to apply a function all list items and performing computations on all listed items.
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.
The list is the most popular sequential data type used in Python. The filter() method mostly used for a list 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 filter() method will return an iterable object which provides given items when iterated with for loop.
#List to be filtered mylist = [ 2 , 5 , 4 , 6 , 8 , 1 , 0 ] #Filter Function 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. In the following example, the list named mylist contains items which are number. By using the lambda function the items checked if they are odd or not. The [1,3,5,7,9] list contains odd numbers where the lambda function check if the current item is in the given mylist. This example also shows us that the filter function can be defined inside the filter function call.
#List to be filtered mylist = [ 2 , 5 , 4 , 6 , 8 , 1 , 0 ] #Lambda function to filter list odd_numbers= filter( lambda number: number in [ 1 , 3 , 5 , 7 , 9 ] , mylist ) for number in odd_numbers: print( number )