DEV Community

Cover image for Python Anonymous Lambda Functions
pavanbaddi
pavanbaddi

Posted on • Edited on

Python Anonymous Lambda Functions

Lambda in python is referred to as anonymous functions. They are single-line function and can accept any number of parameters.

Note : Lambda functions cannot be multi-line. For more details go to this post writen by Guido van van Rossum, creator of python.

Syntax

lambda parameter1,parameter2: processing inputs

To create a lambda function we need to use lambda keyword at the start followed by parameters.

x = lambda : 'This is anonymous function without paramters'

print(x()) #calling lambda function

#PYTHON OUTPUT
This is an anonymous function without parameters

Another example to calculated percentage.

percentage = lambda marks_secured, tot_marks :  (marks_secured/tot_marks)*100

print('{}%'.format(percentage(450,600)))

#PYTHON OUTPUT
75.0%

Application of Lambda function

Lambda functions can be used in sorting

num = [
    [12],
    [10],
    [13],
    [8],
]

print(sorted(num,key= lambda e:e[0]))

#PYTHON OUTPUT
[[8], [10], [12], [13]]

Lambda functions can be used inside another function. The below example increases the value to +2.

def increamentor():
    return lambda a: a+2

k=increamentor()
print(k(4))

#PYTHON OUTPUT
6

This article was taken from Python Lambda Functions

Top comments (0)