Python filter() Function
The filter() function applies the specified function to all the elements of the sequence and returns the element for which the function returns true.
After performing the operation, it returns the iterator/sequence as the result.
Syntax:
filter(function, iterable)
Parameters:
Function | This is the name of the function without parenthesis. |
Iterable | Any sequence like list, tuple, etc |
Example:
def even_numbers(n):
if n % 2 == 0:
return True
else:
return False
numbers = [1,2,3,4,5,6,7,8]
output = filter(even_numbers,numbers)
print(list(output))
Processing Return value:
The map() function returns the object of the map class. We can process this data in two ways:
- Using a for loop to iterate through the return values.
- Using list(), tuple() functions to convert output to the list, tuple, etc.
1.
Using a for loop to iterate through the return values.
def even_numbers(n):
return n % 2 == 0
numbers = [1,2,3,4,5,6,7,8]
output = filter(even_numbers,numbers)
for num in output:
print(num)
2.
Using list(), tuple() functions to convert output to the list, tuple, etc.
def even_numbers(n):
return n % 2 == 0
numbers = [1,2,3,4,5,6,7,8]
output = filter(even_numbers,numbers)
print(list(output))
The filter() function with lambda
The filter function is commonly used with the lambda function. This is the most efficient use of the filter function. In this example, we will use the lambda function to filter out the odd numbers and the even numbers from the list.
numbers = [1,2,3,4,5,6,7,8,9]
odd_numbers = filter(lambda x: x%2 == 1, numbers)
print("Odd Numbers =",list(odd_numbers))
even_numbers = filter(lambda x: x%2 == 0, numbers)
print("Even Numbers =",list(even_numbers))
The filter() function with custom functions
The filter function can be used with the custom functions. In the below example, we are finding out the odd and even numbers, but this time we have created our own custom functions. These custom functions are called using the lambda function.
def even_numbers(num):
return num%2 == 0
def odd_numbers(num):
return num%2 == 1
numbers = [1,2,3,4,5,6,7,8,9]
odd = filter(lambda x: odd_numbers(x), numbers)
print("Odd Numbers =",list(odd))
even = filter(lambda x: even_numbers(x), numbers)
print("Even Numbers =",list(even))
Filter with None
The same filter() function can be used with the None also, when we use the filter function with the none, all the falsy values, which means the values that will return false will be removed.
my_list = [1,2,'a','b',0,'0','']
new_list = filter(None, my_list)
print(list(new_list))