Wednesday, February 5, 2020

Lambda in Python

Lambda Function

What is a lambda function?

A lambda is a small function of an unknown name (nameless). There can be only one expression in the lambda function. We can also provide arguments to the lambda function as a normal function. Lambda function returns the results on executing this expression.

The ‘lambda’ operator is used to declare a lambda function. The syntax for lambda function is,

lambda argument: expression

Lambda functions are very much like inline functions in C/C++. We can also provide one or multiple arguments to a lambda function.

lambda function python

The length of the code is reduced significantly using lambda functions,

y=(lambda x:x*x)(5)


For example

#lambda function demo
x=lambda i:i//2

print('2. Multiple arguments=======================')
y=lambda i,j:i+j

print('3. Multiple arguments=======================')
print('Sum of maximum in three lists [1,2,3],[4,1,7],[3,5,6]')
z=lambda l1,l2,l3:max(l1)+max(l2)+max(l3)

1. lambda====================================
2. Multiple arguments=======================
3. Multiple arguments=======================
Sum of maximum in three lists [1,2,3],[4,1,7],[3,5,6]

Why and where to use lambda functions

The utility of a lambda function is best described with the use inside other functions anonymously. The lambda functions are generally used as an argument to the higher-order functions as arguments. Lambda functions can also be used in situations, where small evaluations are needed to pass to other functions.

The lambda functions are passed as parameters to other functions that expect function objects as parameters such as a map, reduce, and filter functions (see functional programming with Python).

Try yourself: