Signup/Sign In

filter() Function in Python

Posted in Programming   LAST UPDATED: SEPTEMBER 4, 2021

    The filter() function in Python is a built-in function that filters a given input sequence(an iterable) of data based on a function which generally returns either true or false for data elements of the input sequence.

    For example, if we have a list with some random numeric values and a function to check whether a given number is odd or not, then we can use the filter() function, pass the list(an iterable) and the function to check for odd numbers to it, the filter function will then return us a list of only odd numbers from the given list. Hence the filter() function will test the elements of the list against the function and will filter out the list elements for which the given function returns True.

    The filter() function creates an iterator object out of a given iterable object with only those elements which pass the function or for which the function given in filter() function returns True.


    Syntax of the filter() function:

    Following is the syntax of the filter() function,

    filter(function, sequence/iterable)

    It takes two arguments, first one is a function which should return True or False based on whatever evaluation done on input data. And the second argument expected is an iterable object.

    The function checks whether every element of the sequence is true or false.

    The sequence can be a list, tuple, set, or any other iterable object.

    Important Points to Note:

    1. If the function is not None(i.e. a valid function is provided), this translates to (item for item in sequence/iterable if function(item)).

    2. If the function is None, it translates to (item for item in iterable if item). In that case, all the elements of the given sequence are passed through the filter and are available in the result.

    3. If the function doesn't return anything (or returns None), it returns False for every element of the list, which means none of the element of the sequence is passed through the filter and the result contains an empty object.


    Time for an Example

    In the example below, we have a list of numeric values. And we have a function even_numbers() which returns True if a number passed as a parameter is an even number otherwise returns False. We will be using the filter() function to list down all the even numbers in the given list:

    numbers = [1,2,6,7,13,14,12,17,16,53,67,34,75,48]
    def even_numbers(num):
        if(num%2 == 0):
            return True
        else:
            return False
    
    evenNums = filter(even_numbers, numbers)
    print('Even Numbers are:')
    for num in evenNums:
        print(num)

    Output:

    Even Numbers are:
    2
    6
    14
    12
    16
    34
    48

    Note: In the above code, the function and the iterable have been explicitly mentioned and hence the output was as above.

    What happens when None value is given instead of passing the function as a parameter?

    A random list of data has been created below, which consists of integers, strings, and Boolean values. When the function parameter to the filter function is None it filters out data based on whether the element is True or False and returns the element based on the same condition. Therefore, in the example below, all the elements of the list are present in the result:

    new_list = [0, 1, 'a', 'B', False, True, '0', '4']
    filteredList = filter(None, new_list)
    print('Filtered elements')
    for element in filteredList:
        print(element)

    Output:

    Filtered elements
    1
    a
    B
    True
    0
    4
    

    What happens if the funtion doesn't return anything?

    If the function passed to the filter() function does not return anything than all the elements of the sequence are evaluted as False. For example,

    numbers = [1,2,6,7,13,14,12,17,16,53,67,34,75,48]
    def even_numbers(num):
        # do something but dont return
        pass
    
    evenNums = filter(even_numbers, numbers)
    print('Even Numbers are:')
    for num in evenNums:
        print(num)

    Output:

    Even Numbers are:
    

    filter() Function with Lambda

    In the examples above, we learned the basic use of filter() function. The filter function is most commonly used with the lambda function so as to separate out elements of a data structure like tuple, list or set etc and store them in a different data structure. In a lambda function, the function is not defined separately, rather the function body is present as a parameter to the filter function.

    In the example below, the filter function has a lambda function as its first parameter and a sequence of data. The lambda function checks whether a number is odd, and if it is odd, the number passes the filter. Using the filter() function like this returns an object of the filter function with all the parameters set and if we want to see the result, then we have to create list of the result, as shown in the example below.

    sequence_of_int = [ 1, 2, 4, 5, 7, 8, 9, 10, 13] 
    filter_function = filter(lambda x: x % 2 == 1, sequence_of_int)
    print(list(filter_function))

    Output:

    [1, 5, 7, 9, 13]
    

    Quick Fact

    If you have Python 3.x, the filter method returns a generator, i.e which can be traversed through. If you are using Python 2.x version, the filter method returns a list.

    filter(function, data) in Python 2.x version is same as list(filter(function, data)) in Python 3.x version


    Conclusion

    In this post, we learned how a filter function can be useful in filtering out data based on a specific condition or based on whether a data element in a sequence in True or False.

    You may also like:

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:PythonPython Library FunctionsProgramming
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS