Lambda function in Python

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.

Syntax
lambda_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

Passing Multiple value

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 using Normal function

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

Lambda Function Used with "map()" function

In map() function,list as arguments for lambda function and it return in the form of list.

Example
li=[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]

Lambda Function Used with "filter()" function

In filter(function,sequence) function takes the sequence and filter according the condition.

Example
li=[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]

Lambda Function Used with "reduce()" function

In reduce(function,sequence) function take any sequence and pick two element and apply the operation and it is part of functools module.

Example
from 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