lambda with filter() function in python by R4R Team

lambda function-
-In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

Syntax-
lambda argument:expression

filter() function-
- 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)

Lambda with filter function-
In filter we require a function for argument, so at the place of the function, we create a lambda function which return True according to given expression.

Syntax-

filter(lambda arg:exp,sequence)


program-

#filter all integer value from the list
l=[1,2,3,4,"one",'two',1.2000]
print("list is",l)
a=filter(lambda x:type(x)==int,l)
print("List after filtering")
print(list(a))

#filter all even number from the list
a=filter(lambda x:x%2==0,[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.2000] then by filter() we pass each value of the list to the lambda function then by type(x)==int return True only on integer value and other value is discard.
-then in other case we have a list [1,2,3,4] and condition in lambda is x%2==0 which return True on even value and other value are discard.




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!