filter() function in python by R4R Team

- filter() is a python function which filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

Syntax-

filter(function,sequence)

-It works on the return value by the function, if function return True then filter consider that element otherwise discard.

Example-

we have a function which return True on even number false on odd number
list is [1,2,3,4]
then
filter(function,l) will return [2,4]


program-

l=[1,2,3,4,"one",'two',1.2000]

def func(n):
if type(n)==int:
return True
return False

print("list is",l)
a=filter(func,l)
print("List after filtering")
print(list(a))

def geteven(n):
if n%2==0:
return True
return False

a=filter(geteven,[1,2,3,4])
print("After even filteration, list become")
print(list(a))


output-

list is [1, 2, 3, 4, 'one', 'two', 1.2]
List after filtering
[1, 2, 3, 4]
After even filteration, list become
[2, 4]


-In this program, we have a list [1, 2, 3, 4, 'one', 'two', 1.2] , then firstly we filter all integer value by filter(func,l) func() function return True on integer value, then we have a list [1,2,3,4] then we filter all even element from the list by filter(geteven,l), where geteven return True on even values.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!