How to Use If, Else and Elif in Lambda Functions in Python

Python lambda function is defined without a name. Instead, the anonymous functions are defined using a lambda keyword.

Syntax of Lambda function

lambda arguments: expression

The lambda functions can have any number of parameters but only one expression. That expression is evaluated and returned. Thus, lambda functions can be used wherever a function object is required.

cube = lambda x: x * x * x

print(cube(11))

Output

1331

Using if-else in the Lambda function

The if-else in lambda function syntax is the following.

lambda <arguments> : <Return Value if condition is True> 
                     if <condition> else <Return Value if condition is False>

For example, let’s create the lambda function to check whether the given value is between 11 and 22.

verify = lambda x: True if (x > 11 and x < 22) else False

print(verify(15))
print(verify(22))
print(verify(21))

1 thought on “How to Use If, Else and Elif in Lambda Functions in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.