Python filter() function examples

Last updated on March 5, 2021 A Goodman Loading... Post a comment

In this article, we will cover the fundamental of the filter() function in Python and explore 4 practical examples of using it.

Overview

Syntax:

filter(function, iterable)

Paramerters:

  • function: The function that tests whether each item of an iterable true or not.
  • iterable: The iterable to be filtered

The filter() function returns a filtered object, which is an iterable. We can use a function like list(), tuple() to make a list or tuple of all the items returned in a filter object.

Example 1

The tiny program below return the odd numbers from a given list.

The code:

my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
def check_odd(input):
    return input % 2 != 0

odd_numbers = list(filter(check_odd, my_numbers) )
print(odd_numbers)

Output:

[1, 3, 5, 7, 9, 11]

Example 2

This examples filters the names that start with B.

The code:

users = ['Andy', 'Bobby', 'Kindacode', 'Harry Potter',
         'Voldermort', 'Brady', 'Bingo', 'Bem']

def start_wtih_b(name):
    return name.startswith('B')

b_names = filter(start_wtih_b, users)
print(list(b_names))

Output:

['Bobby', 'Brady', 'Bingo', 'Bem']

Example 3

In this example, we have a list of dictionaries that contain information about some people, including name and age. Our task is to filter out the adults (over 18 years old) from that list.

The code:

people = [
    {
        "name": 'A',
        "age": 10
    },
    {
        "name": "B",
        "age": 5
    },
    {
        "name": "C",
        "age": 40
    },
    {
        "name": "D",
        "age": 30
    }
]

def is_mature(person):
    return person["age"] >= 18

results = filter(is_mature, people)
print(list(results))

Output:

[{'name': 'C', 'age': 40}, {'name': 'D', 'age': 30}]

Example 4

This example shows you how to use the filter() function with the lambda expression.

The following program will find the numbers that are equal or greater than 5 from a given list:

numbers = [4, 3, 9, 10, 11, 3, 5]

result = filter(lambda x: x >= 5, numbers)
print(list(result))

Output:

[9, 10, 11, 5]

Conclusion

We have gone through the syntax and a few examples of the filter() function in Python. Understanding it will help you filter for items in varying complexities of data structures.

If you would like to explore more interesting things in Python, take a look at the following articles: Examples of using map() function in Python 3, Extract all links from a webpage using Python and Beautiful Soup 4, 5 essential List Methods in Python 3, How to run Python 3 with Nodemon on Mac.

You can also check out our Python category page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x