filter(): matching elements from an iterable

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 
Output
[82, 40]
We used % modulus operator here.

Using string

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 .
def my_check(x):
    if x.islower():
        return True
    else:
        return False
my_str='Plus2Net'                 # input string object
my_filter=filter(my_check,my_str) # used filter 
print(list(my_filter))            # output 
Output
['l', 'u', 's', 'e', 't']

Using lambda

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.
my_str='Plus2Net'
my_filter=filter(lambda x: x.islower(),my_str)
print(list(my_filter))
Output
['l', 'u', 's', 'e', 't']

Data type of filter() output

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:
data = [0, "", None, "Python", [], '0', {}]
filtered_data = filter(None, data)
print(list(filtered_data))
This will output:
['Python', '0']
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()

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer