Python
In this tutorial we will learn about lambda function in Python.
A lambda function in Python is an anonymous function which can take multiple argument but must have only one expression.
Following is the syntax of a lambda function.
lambda arguments: expression
Where, lambda
is the keyword we use to create a lambda function. arguments
is the argument that we pass to the function and expression
is some expression for the lambda function.
In the following Python program we are creating a lambda function that takes a string value and prepares a greeting message.
# lamda function
greeting = lambda str: "Hello %s!" %str
message = greeting('Yusuf')
print(message) # Hello Yusuf!
In the above code we are assigning the lambda function to greeting
variable. Then we are passing a string 'Yusuf'
to the greeting lambda function which is giving back the string 'Hello Yusuf!'
and it is assigned to the message
variable. Finally we are printing the result.
Lambda function is generally used in scenarios were we want to have an anonymous function for a short duration.
We can use lambda function inside a function.
In the following Python program we are returning a lambda function from inside a function which is later used to get the double value of a given number.
# func
def myFunc():
# return lambda function
return lambda n: n * 2
doubleIt = myFunc()
print(doubleIt(1)) # 2
print(doubleIt(2)) # 4
print(doubleIt(3)) # 6
In the above code we have a lambda function inside the myFunc
function.
We call the myFunc
function and it returns the lambda function which we assign to the doubleIt
variable.
Finally we call the doubleIt
function and pass integer value which gets doubled and are printed.
We can even convert the above code to give us a more dynamic multiplier.
In the following Python program we are creating a dynamic multiplier using lambda function.
# func
def multiplier(N):
# return lambda function
return lambda x: x * N
doubleIt = multiplier(2)
tripleIt = multiplier(3)
quadIt = multiplier(4)
print(doubleIt(3)) # 6
print(tripleIt(3)) # 9
print(quadIt(3)) # 12
Print cube of a number using lambda function.
Cube of N = N x N x N
So, cube of 3 = 3 x 3 x 3 = 27
In the following Python program we are creating a lambda function that will be used to compute cube of a number.
# lambda function
cube = lambda N: N * N * N
print(cube(1)) # 1
print(cube(2)) # 8
print(cube(3)) # 27
print(cube(4)) # 64
print(cube(5)) # 125
ADVERTISEMENT