The filter function in Python

The filter function is used to build an iterator (a list, tuple etc.) after taking an iterable and a function as parameters. The built iterator contains only those items that returned as true after passing to the function.

Filter example with list Example with Lambda

For example, we have a list that contains years:

Yr_List = [1980, 1988, 1990, 1992, 1993, 1998, 2002]

We want to construct a new list that contains only leap years from the above list. So, this is where the filter function can play its role.

As such, filter function requires an iterator (a list in that case) and a function. The function will take each element of the Yr_List and check whether it’s a leap year or not. The items that are returned as true will be filtered out and filter function will return a new list containing only leap years.

See the code and output of this example in the coming section, first let us have a look at the syntax of the filter function.

Syntax of filter function

Following is the syntax of using the Python filter function:

filter(function, iterable)

  • A function can be a lambda, user-defined etc.
  • An iterable can be an iterator, sequence or container that supports iteration. For example, a list, tuple, set etc.

An example of filter list to get leap years using lambda

Using the same list as explained in the first section; in this example, we will filter a list that contains leap and non-leap years. The lambda function is used and list items are passed that contains the year items.

The filter method will short-list only those items that return as true i.e. leap years. Have a look:

See online demo and code


Python filter

You can see, the new list built after using the filter method displayed only three items that are leap years.

An example of comparing two lists and filtering unmatched items

In this example, two lists are created and compared by using the filter method. The returned list constructed after using the filter method contains unmatched items from the first list. Again, the lambda function is used in the filter method:

See online demo and code


Python filter lists

You can see, the new list only contains items that do not exist in the List_2.

An example of filter with set

In this example, a set is created with a few items. A function is created to return the numbers that can be divided by 3. In the filter method, the set and functions are passed that returns an iterator containing only those numbers that can be divided by 3 in the given set.

Finally, the returned iterator is converted to a set that displayed the filtered numbers:

See online demo and code


Python filter set

You can see, the print function displays only numbers that can be divided by 3 in the set.