Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python filter() Function



The Python filter() function returns a object list containing elements of the specified iterable filtered by the specified function. An iterable can be any data structure like list, tuple, set, string and dictionary etc. Along with this, a range() function can also be used as an iterable.

Syntax

filter(function, iterable)

Parameters

function Required. function to filter elements from iterable
iterable Required. iterable object like list, tuple, set, string , dictionary and range() etc.

Example: filter() for even number

In the example below, filter() function is applied on a list to return a list containing only even numbers.

def MyFunc(x):
  if(x%2==0):
    return x

MyList = [1, 3, 6, 8, 9, 12, 35, 47]

NewList = list(filter(MyFunc, MyList))
print(NewList)

The output of the above code will be:

[6, 8, 12]

Example: using lambda function with filter function

Here, the filter() function is used with a lambda function to return a list containing only even numbers.

MyTuple = [1, 3, 6, 8, 9, 12, 35, 47]

NewList = list(filter(lambda x: x%2 ==0 , MyTuple))
print(NewList)

The output of the above code will be:

[6, 8, 12]

❮ Python Built-in Functions

5