What Is The Lambda Function In Python?

What Is The Lambda Function In Python?

Published on October 01 2023

In this tutorial, we will learn about lambda expression and functions in Python with an example in detail. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Lambda function is an anonymous function in Python - a function that does not have a name.
  • It can have any number of arguments, but only one expression or statement.
  • To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’.

Usage

  • It is generally used in situations requiring an anonymous function for a short time period.
  • They are used for creating function objects during runtime.

Example

  • can be used in either of the two ways:
  1. Assigning lambda functions to a variable
    mul_func = lambda x,y : x*y
    print(mul_func(6, 4))
    # output
    24
  2. Wrapping lambda functions inside another function
def myWrapperFunc(n):
    return lambda a : a * n
    
mulFunc = myWrapperFunc(5)
print(mulFunc (3)) 
# output
15

To know about it, please refer to the official documentation website - official website.