43 Lambda function in Python
'''
1. Lambda is a another way to create a function.
2. Lambda is a one line anonymous function it doesn't contains name.
3. Using lambda we can do only one expression.
'''
## Lambda with out arguments
#add = lambda : 3 + 5
#r = add()
#print(r)
## Lambda with arguments
#add = lambda a,b: a + b
#r = add(2, 33)
#print(r)
## Lambda with if and else
add = lambda a,b: a + 10 if a > 5 else b + 100
print(add(6,6))
------lambda with Map-----
# Double the value of each element
myList = [10, 25, 17, 9, 30, -5]
myList2 = map(lambda n : n*2, myList)
print myList2
------lambda with filter------
# Filters the elements which are even numbers
myList = [10, 25, 17, 9, 30, -5]
myList2 = list(filter(lambda n : (n%2 == 0), myList))
print(myList2)
------Use lambda function with filter()-----
The Python built-in filter() function accepts a function and a list as an argument.
It provides an effective way to filter out all elements of the sequence.
It returns the new sequence in which the function evaluates to True.
#program to filter out the tuple which contains odd numbers
lst = (10,22,37,41,100,123,29)
oddlist = tuple(filter(lambda x:(x%3 == 0),lst))
print(oddlist)
-----Using lambda function with map()-----
The map() function in Python accepts a function and a list.
It gives a new list which contains all modified items returned by
the function for each item.
lst = (10,20,30,40,50,60)
square_list = list(map(lambda x:x**2,lst))
print(square_tuple)
Comments
Post a Comment