Leo Umesh avatar

Lambda Function in Python Programming

leoumesh

Published: 03 Dec 2021 › Updated: 03 Dec 2021Lambda Function in Python Programming

Lambda Function in Python Programming

image.png

Image Source

In python , lambda functions are also known as one line function or anonymous function as they are defined with no name. Using lambda functions reduce number of lines in the code and also the execution speed of your code becomes very faster. In the below example we will see the simple example of the lambda. But before that lets see the basic syntax of the lambda functions:

lambda arguments: expression

It can accept any number of arguments but only one expression that can be evaluated. The lambda function doesn't contain any return statement and by default it will return the value. Since functions are also objects in python, you need to store them in the variables. The following is the simple example to find the cube of a number using the concept of lambda.

a = lambda b:pow(b,3)

print(a(5))

The output of this program will be:

image.png

Lets see another example that consists of a two arguments and that finds the power of first number to the second number.

a = lambda b,c:pow(b,c)

print(a(5,4))

The final output on execution will be:

image.png

Now you may have written a program that shows whether a given number is even or odd using function. Although the program is simple, it typically includes significant lines of code. Lets see how lambda can be used to write such programs.

a = lambda b:"Even number" if b%2==0 else "Odd Number"

print(a(7))

The output of this code is:

image.png

Leave Lambda Function in Python Programming to:

Written by

I am just a passionate blogger.

Read more #hive-163521 posts


Best Posts From Leo Umesh

We have not curated any of leoumesh's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Leo Umesh