Lambda Function in Python Examples

 

To define anonymous functions we can use lambda key word.

Syntax

lambda arguments: expression

Here, lambda function can take more than one argument but it can have only one expression.

Example

Takes one argument x,add 5 to x and returns the result.

f = lambda x: x + 5
print(f(10))

Output
15

Example


Takes two arguments x and y, adds them and returns the result.

f = lambda x, y : x + y
print(f(1020))

Output
30

The above example can also be written as bellow

(lambda x, y: x + y)(10,20)

Where to Use lambda function


The lambda function can be passed as an argument to another function.
def func(n):
  return lambda x: x + n

We can use the same function to define a function that always doubles the number we input.

def func(n):
  return lambda x: x + n


double = func(2)
print(double(10))

Output
20

We can use the same function to define another function that always triples the number we input.

def func(n):
  return lambda x: x + n


triple= func(3)
print(triple(10))

Output
30

Here the same function func()  is used for both the functions to make double and triple of the inputted number.

Useful Resources:

Comments