Python Lambda

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Syntax is – lambda arguments expression

1. EXAMPLES OF LAMBDA

1.1 ADDITION IN LAMBDA IN PYTHON

x lambda function that adds 20 to the number passed in as an argument and print the result

ans = lambda x : x + 20
print(ans(5))

OUTPUT:

ADDITION IN LAMBDA IN PYTHON
OUTPUT – ADDITION IN LAMBDA IN PYTHON

1.2 MULTIPLICATION IN LAMBDA IN PYTHON

ans = lambda x, y : x * y
print(ans(5, 6))

OUTPUT:

MULTIPLICATION IN LAMBDA USING PYTHON
OUTPUT – MULTIPLICATION IN LAMBDA USING PYTHON

1.3 ADDING THREE ARGUMENTS IN LAMBDA IN PYTHON

ans = lambda x, y, z : x + y + z
print(ans(5, 6, 2))

OUTPUT:

ADDING THREE ARGUMENTS IN LAMBDA IN PYTHON
OUTPUT – ADDING THREE ARGUMENTS IN LAMBDA IN PYTHON

2. WHY USE LAMBDA FUNCTIONS?

The power of lambda is better shown when you use them as an anonymous function inside another function.

2.1 FUNCTION IN LAMBDA IN PYTHON

def myfunction(num):
    return lambda x : x * num
ans = myfunction(2)
print(ans(11))

OUTPUT:

FUNCTION IN LAMBDA IN PYTHON
OUTPUT – FUNCTION IN LAMBDA IN PYTHON

2.2 LAMBDA FUNCTION IN PYTHON

def myfunc(num):
    return lambda x : x * num
ans = myfunc(2)
ans2 = myfunc(3)
print(ans(11))
print(ans2(11))

OUTPUT:

LAMBDA FUNCTION IN PYTHON
OUTPUT – LAMBDA FUNCTION IN PYTHON

Leave a Reply

Your email address will not be published. Required fields are marked *