Python filter() function

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

The filter() function takes a function and a sequence as arguments and returns an iterable, only yielding the items in sequence for which function returns True. If None is passed instead of a function, all the items of the sequence which evaluates to False are removed. The syntax of the filter()  is as follows:

Syntax: filter(function or None, iterable) --> filter object

Here is an example:

Python 3

To produce the result at once we can use the list() function.

Python 3

In Python 2, filter() returns an actual list (which is not the efficient way to handle large data), so you don’t need to wrap filter() in a list() call.

Python 2

Here are some other examples.

Python 3

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Your email address will not be published. Required fields are marked *