DEV Community

Cover image for Python Anonymous Lambda Functions
pavanbaddi
pavanbaddi

Posted on • Edited on

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay