Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

How to Use the Filter Function

Give Feedback

In this lesson, you’ll see how to use filter(). The built-in function filter() is another classic functional construct and can be converted into a list comprehension.

It takes a predicate as a first argument and an iterable as a second argument. It builds an iterator containing all the elements of the initial collection that satisfies the predicate function.

Comments & Discussion

John Laudun on Sept. 3, 2019

This has been really useful for someone like me who is slowly making his way from novice to something like apprentice with aspirations for craftsman. I am curious about one very small bit: if the goal of lambda functions is to have things in one line, why not above_avg = list(filter(lambda x : x > mean(nums), nums))?

blu on Sept. 5, 2019

i suspect because mean(nums) would be evaluated len(nums) times

Become a Member to join the conversation.