filter(function, iterable) Construct an iterator using the matching elements from the iterable object
function
(required ) , Each element is checked through the function
iterable
( required ), iterable object
We can pass each element of the iterable object through the function and get only the elements which are matching to condition or returning True.
Example 1
Create one user defined function my_check(). This function receives one element and check if it is divisible by 2 or not. The function will return True if the element is divisible by 2 ( even number ) or it will return False if not divisible by 2.
def my_check(x):
if x%2==0:
return True
else:
return False
my_list=[5,82,40,37] # created a list
my_filter=filter(my_check,my_list)# Used filter
print(list(my_filter)) # display elements
We know string is also iterable object so we will use one char as input to a function and filter out ( by using if else ) all lower case chars. We will use the string method islower() to check the status of the input char. This method islower() will return True for lower case chars and return False for upper case chars .
In above code we have used one user defined function my_check() to check each char of the iterable object. We can also use lambda in place of my_check() function to get the same functionality.
By using type() we can findout the data type of the output.
def my_check(x):
if x%2==0:
return True
else:
return False
my_list=[5,82,40,37] # created a list
my_filter=filter(my_check,my_list)# Used filter
print(type(my_filter)) # <class 'filter'>
We can use short code for the function my_check() like this
def my_check(x):
return True if x%2==0 else False
Using filter() with None
When the function argument is None, the function defaults to the identity function, filtering out any elements in the iterable that are False in a boolean context. Here's an example:
This demonstrates that filter(None, data) removes elements that are False in a boolean context, such as 0, empty strings, empty lists, and None.
Benefits of Using filter()
Conciseness: It provides a concise way to filter elements from a collection based on a condition.
Flexibility: Can be used with any iterable and allows for complex filtering logic through custom functions.
Readability: Enhances the readability of the code, making it clear that the operation is filtering elements based on a specified condition.
In summary, the filter() function is a powerful tool for extracting elements from a collection that meet certain criteria, making code more readable, concise, and expressive.
«All Built in Functions in Python slice()