filter

Full name
filter
Library
Built-in
Syntax

filter(function, iterable)

Description

The filter function takes a function and an iterable object as arguments and returns the elements of the iterable that satisfy the function (those for which the function returns the boolean True). We can say that filter filters the iterable leaving only those elements that satisfy the indicated function.

If the function passed as the first argument is None, the identity function is applied. That is, the same value that is received as an argument is returned. This means that the elements of the iterable that take the value True will pass the filter, and those that take the value False will not.

As indicated in the Python documentation, this function "remembers a for loop" (since it goes through all the elements of the iterable checking if they meet the condition in question or not) but "it is a built-in and faster function".

Parameters
  • function: function that the elements must satisfy to be returned as result of the function. The result of this function after applying it to each element should be a boolean.
  • iterable: object whose elements are to be evaluated.
Result

The filter function returns an iterable.

Examples

If we start from a list of positive and negative numbers:

numbers = [4, -2, 6, 3, -1, 6]

...we can filter it to leave only positive numbers with the following code:

def is_positive(n):
    return n >= 0

filter(is_positive, numbers)

<filter at 0x27717a57a90>

We check that the result is an iterable that we can convert, for example, into a list to observe its content:

list(filter(is_positive, numbers))

[4, 6, 3, 6]

In a case like this, it is easier to define the function to be applied as a lambda function directly as an argument to filter:

list(filter(lambda n: n> = 0, numbers))

[4, 6, 3, 6]

If the value None is passed as the first argument, the identity function is applied. For example:

elements = [True, False, True, False]

list(filter(None, elements))

[True, True]

We can confirm that only the values of elements that took the value True have been kept.

In the case that the elements are numbers, those that take the value zero will be considered False, and the rest True:

numbers = [2, 0.5, 0, -0.1, 0, -3]

list(filter(None, numbers))

[2, 0.5, -0.1, -3]

If the elements are text strings, empty strings are considered False, and the rest are True. For example, we start from the following list of texts:

texts = ["Python", "", "and", "Artificial", "", "Intelligence"]

Note that an empty text string (the second element) and one that includes a blank space (and not empty, therefore) have been included. If we apply the filter function we obtain the following:

list(filter(None, texts))

['Python', 'and', 'Artificial', '', 'Intelligence']

We confirm that all texts have passed the filter except the empty string.

Submitted by admin on Wed, 01/13/2021 - 14:11