What does the filter( ) function do?


#1

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.


FAQ: Learn Python - Advanced Topics in Python - Anonymous Functions