lambda is a keyword in Python. There is an alternative method for creating functions, which is a small part of an anonymous function. It also takes zero or more than one argument and has only one expression.
Syntaxlambda_argument_return: expressions
expressions will executed and return in lambda_argument_return.
multiply=lambda mul:mul*500
number=int(input("Enter the Number:"))
print("After Multiplying with 500.")
print(multiply(number))
Output
Enter the Number: 5 After Multiplying with 500. 2500
multiply=lambda n1,n2,n3:n1*n2*n3 number1=int(input("Enter the Number1:")) number2=int(input("Enter the Number2:")) number3=int(input("Enter the Number3:")) print("After Multiplying with three Number.") print(multiply(number1,number2,number3))Output
Enter the Number1: 10 Enter the Number2: 20 Enter the Number3: 30 After Multiplying with three Number. 6000
Lambda function are used with normal function for batter performance of anonymous function.
def multi(): return lambda n1,n2:n1*n2 multiply=multi() number1=int(input("Enter the Number1:")) number2=int(input("Enter the Number2:")) print("After Multiplying with two Number.") print(multiply(number1,number2))Output
Enter the Number1: 10 Enter the Number2: 20 After Multiplying with two Number. 200
In map() function,list as arguments for lambda function and it return in the form of list.
Exampleli=[1,2,3,4,5,6,7,8,9,10] new_list=list(map(lambda a: a**2,li)) #printing the new list. print("New List.",new_list)Output
New List: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In filter(function,sequence) function takes the sequence and filter according the condition.
Exampleli=[1,2,3,4,5,6,7,8,9,10] filter_list=list(filter(lambda a: a%2==0,li)) # Printing the filtered list. print("Filter List:",filter_list)Output
Filter List: [2, 4, 6, 8, 10]
In reduce(function,sequence) function take any sequence and pick two element and apply the operation and it is part of functools module.
Examplefrom functools import reduce li=[1,2,3,4,5,6,7,8,9,10] red=reduce((lambda a,b: a*b),li) #printing the reduced list. print("Result:",red)Output
Result: 3628800