Python filter()

Filed Under: Python

Python filter() function is used to filter the elements of an iterable based on a function. This function returns filter object that is an iterator.

Python filter()

Python filter() function syntax is:

filter(function, iterable)

function will be called on iterable elements and if it returns True then they will be part of the returned iterator.

We can also pass the function as None, in that case, standard truth testing rules will be followed to determine if the iterable elements are True or False. You can get more details about them in Python bool example.

Python filter() example

Let’s define a function to check if the input number is even or not. It will return True if the number is even, else False.

We will also define a utility function to print elements of the iterator.

def is_even(x):
    if x % 2 == 0:
        return True
        return False

def print_filter_items(my_filter):
    for item in my_filter:
        print(item, end=' ')

Let’s use filter() function to get an iterator of even numbers only from the input iterable of integers. We will use tuple and list for our example, both of them are iterable.

l1 = [1, 2, 3, 4, 5]
fl = filter(is_even, l1)

t = (1, 2, 3, 4, 5)
fl = filter(is_even, t)


<class 'filter'>
2 4 
2 4 

Python filter() example with None function

t = (True, False, 1, 0, 0.0, 0.5, '', 'A', None)
fl = filter(None, t)


True 1 0.5 A

Notice that zero, empty string, False and None are filtered out because their boolean value is False.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages