What does the filter( ) function do?

Question

What does the filter( ) function do?

Answer

filter() is a built-in function available in Python that takes two arguments, a function and an iterable, and returns a list of elements from the iterable for which the function returns true.
In the example shown in this exercise (and below), the elements left after the filter() does its job are those that the lambda returned True for. The elements resulting in True are those that are divisible by 3 with no remainder.

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)

The documentation for this built-in function can be found here.

1 Like

Is lambda a part of the filter() function? If not, can it be omitted from the print statement, and what is its use?

The filter function takes two arguments, a callback function, and an iterable.

When written inside the argument, we use an anonymous function, which is what lambda is. We can also write a standalone function and then write only the reference in the argument.

def foo(x):
    return x != 42

Note the above is a predicate function.

print ([*filter(foo, [7, 14, 21, 35, 42, 49, 56])])
                 ^
              callback
              reference
>>> print ([*filter(foo, [7, 14, 21, 35, 42, 49, 56])])
[7, 14, 21, 35, 49, 56]
>>> 
2 Likes

you said we can also write a standalone function and then write only the reference in the argument, but in your example you still wrote the filter function and the reference function together. so can we not write the reference function w/ the filter function(is the filter function the standalone function)?
added note: i’m re-reading your response, mtf. I’m a little confused on which is the standalone function and which is the reference; you said we use an anonymous function inside the argument, then create def foo(x) and call it a predicate function, but put it inside the argument and call it the callback reference…is it just all of them?

The standalone function is foo(). The print statement contains a type of comprehension called a spread. It will unpack the iterator that filter returns.

filter invokes foo on every value in the list that we passed in.