Trusted answers to developer questions

How to use the filter() method in Python

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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)

RELATED TAGS

python
lambda
map
filter
apply
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?