How to use the filter() method in Python

The filter() function facilitates a functional approach to Python programming. It takes as an argument a function and an iterable and applies the passed function to each element of the iterable. Once this is done, it returns an iterable.

The filter() function is similar to a for-loop in Python but is much fast as a built-in function.


Syntax

Here is the function signature for the filter() function in Python:

# function signature for the filter() method
returned_iterable = filter(function, iterable)

As described above, the filter() function takes the following two arguments as input:

  • function: A valid, pre-defined function. This is a lambda function in most cases.

  • iterable: This is an iterable object (e.g. list, tuple, dictionary).

Returned: An iterator to the filtered items’ iterable object.

svg viewer

Examples

Let’s take a look at a couple of examples of how the filter() method works:

1. Using a lambda function

myList = [10, 25, 17, 9, 30, -5]
# Returns the elements which are multiples of 5
myList2 = list(filter(lambda n : n%5 == 0, myList))
print(myList2)

2. Using a pre-defined function

# Returns the elements which are multiples of 5
def multipleOf5(n):
if(n % 5 == 0):
return n
myList = [10, 25, 17, 9, 30, -5]
myList2 = list(filter(multipleOf5, myList))
print(myList2)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved