Python Lambda Function

The Lambda function in Python programming which is also known as anonymous function is a function without any name. It is a small function restricted to a single line. Like the normal function in Python, it can take multiple arguments but the function body should contain only one expression.

Regular Python functions are declared using the def keyword and a lambda function is defined using lambda keyword. Today in this article you will learn how to use the lambda function in your python code.

Why use the lambda function

You can have various reasons to use the lambda function in your Python code for example –

  • You can use a lambda function when you require a nameless function for a short period of time
  • It generally used as the argument to higher-order functions (functions that takes another function as an argument)
  • A lambda function is used as an argument to built-in functions such as map(), filter(), etc
  • The use of the lambda function reduces the number of lines in your code

Syntax of Python lambda function

The syntax of a python lambda function is given below –

lambda arguments : expression

Where lambda is a keyword used to define lambda functions, arguments are the comma-separated arguments passed to the function and the expression is a single expression that will be evaluated and the result will be returned.

Example of Python lambda function

The following examples show the use of the lambda function in Python programming.

Example 1:

In the given example lambda function will take a number as an argument and will return its square.

x=lambda a:a*a
print(x(5))

When you execute this code it will print 25 which is the square of 5.

Example 2:

In our second example, we will pass two numbers as the argument to the lambda function and it will return the sum of both numbers.

x= lambda a,b:a+b
print(x(5,6))

This code will print 11 which is the sum of 5 and 6.

A regular Python function vs lambda function

As discussed earlier a regular Python function is defined using the def keyword and we use the lambda keyword to define lambda function in Python programming. In this section, you will see the difference using the given Python code.

The given program defines a function called cube() that takes a number as an argument and returns its cube.

numbers=[1,2,3,4,5]
def cube(a):
    return a*a*a
numbers_cube=list(map(cube, numbers))
print(numbers_cube)

The same code can be written with the use of the lambda function as it is given below –

numbers=[1,2,3,4,5]
numbers_cube=list(map(lambda a:a*a*a, numbers))
print(numbers_cube)

Here we defined the lambda function and passed it as an argument to the built-in map function. Both of these codes will return the same result i.e. a list containing the cube of numbers. You can see this in the given image –

Ok, that’s all for now. if you have a query then leave it in the comments below.

Leave a Comment