Python filter() with Examples

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:

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.

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.

Output:

Python filter() example with None function

Output:

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

By admin

Leave a Reply

%d bloggers like this: