Python - Lambda Function

Python

Share
python logo

In this tutorial we will learn about lambda function in Python.

What is a lambda function?

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.

About lambda function

  • They can take any number of arguments but must return just one value in the form of an expression.
  • Lambda function can only access global variables and variables in its parameter list.
  • Can't use lambda function to just print value as lambda function must have an expression.

Example of 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.

When to use lambda function?

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

Exercise #1

Print cube of a number using lambda function.

Solution

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
Share