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:

Error: Code Widget Crashed, Please Contact Support

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 ©2025 Educative, Inc. All rights reserved