In this article, we will discuss on Python lambda. Let us have a quick look on the following contents shown below:
- Introduction
- Add two numbers using Lambda
- Sum of 10 natural numbers
- Multiplication
- Smaller of two numbers
Introduction
Lambda functions are the anonymous functions. They are not declared as other functions using the def keyword. They are created using lambda keywords.
Add two numbers using Lambda
sum=lambda x,y:x+y
print("Sum = ",sum(2,7)) #returns Sum = 9
Sum of 10 natural numbers
x = lambda: sum(range(1,8))
#Invoke lambda expression that accepts no arguments but returns a vlue in y
print(x()) #returns 28
Multiplication
#lambda function not assigned to any variable twice
print((lambda x: x*2) (9))
(twice(9)) #returns 18
Smaller of two numbers
def small(a,b):
if(a<b):
return a
else:
return b
sum=lambda x, y: x+y
diff = lambda x, y: x-y
#pass lambda functions as arguments to the regular function
print("Smaller of two numbers = ", small(sum(-3,-2), diff(-1, 2)))
#returns Smaller of two numbers = -5
Lambda takes some built-in functions like filter(),map(),reduce(),etc and we can use them in regular functions. To know more you can refer to this site.