Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Lambda Function


Lambda Function

In Python, the lambda function is a small anonymous function.

Lambda functions take any number of arguments, but they can only contain one expression.

When creating lambda functions, you should always use the lambda keyword.

Syntax

The lambda function executes the expression and returns the result.

lambda arguments : expression

Lambda Function with One Argument

add_numbers = lambda a : a + 1
print(add_numbers(2))
3

In the above example, we are adding 1 to each passed value in the lambda function.


Lambda Function with Multiple Arguments

The lambda function allows multiple arguments.

multiply_numbers = lambda a, b : a * b
print(multiply_numbers(2, 3))
6

In this example, the lambda function takes two arguments and multiplies them.


add_numbers = lambda a, b, c : a + b + c
print(add_numbers(1, 2, 3))
6

Here, the lambda function takes three arguments and adds them.


Python Why Use Lambda Functions?

It is more effective to use lambda as an anonymous function within another function to demonstrate lambda function power.

def python_function(number):
    return lambda a : a * number

multiply_numbers = python_function(2)

# multiply_numbers = python_function(3)
# multiply_numbers = python_function(5)

print(multiply_numbers(3))
6

Here we are doubling the number which passed to the function definition.

Using this function can also be used to triple or multiply any number.