Javaexercise.com

Python filter() Method

Python filter() method is a built-in method. It returns an iterator by using a function that returns True for the given sequence.


Signature

filter(function, iterable)

Parameter Description
function A Function to be run for each item in the iterable
iterable The iterable to be filtered


Return Value

It returns an iterator.


Python filter() Method Example

Let’s first understand, how this method works and what does it return?

#Using filter() method to fetch even values from the list
list1 = [1,2,4,5,6,9]
#Defining method
def getiterable(list2):
     if list2%2==0:
         return True
     else:
         return False
#Calling filter method
result = filter(getiterable,list1)
for val in result:
    print(val)

Output

 2

 4

 6