Python filter() function
Python filter() function
The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true.
Syntax
filter(function, iterable)
Parameter
function: This parameter represents a function to be run for each item in the iterable
Iterable: It represents the iterable to be filtered
Return
This function returns an iterator where the items are filtered through a function to test if the item is accepted or not.
Example 1
#Python program explaining # the filter() function voters_age = [5, 12, 17, 18, 24, 32] def validAge(age): if age < 18: return False else: return True #applying the filter() function adults = filter(validAge, voters_age) for age in adults: print(age)
Output
18 24 32
Example 2
#Python program explaining # the filter() function # a list contains both even and odd numbers. values = [10, 11, 12, 13, 15, 18, 103] print("List: ",values) # filter() returning odd numbers of the list even_val = filter(lambda x: x % 2!=0, values) print("Even Values: ",list(even_val)) # filter() returning even numbers of the list odd_val = filter(lambda x: x % 2 == 0, values) print("Odd values: ",list(odd_val))
Output
List: [10, 11, 12, 13, 15, 18, 103] Even Values: [11, 13, 15, 103] Odd values: [10, 12, 18]