Python Lambda - If Else, Nested If Else


Python Lambda with If Else

In this tutorial, we will learn how to use if else in Lambda function, to choose a return value based on some condition.

Syntax

The syntax of a Python Lambda Function with if else is as shown in the following.

lambda <arguments> : <value_1> if <condition> else <value_2>

value_1 is returned if condition is true, else value_2 is returned. You can have an expression that evaluates to a value in the place of value_1 or value_2.

You can have nested if else in lambda function. Following is the syntax of Python Lambda Function with if else inside another if else, meaning nested if else.

lambda <arguments> : <value_1> if <condition_1> else (<value_2> if <condition_2> else <value_3>)

value_1 is returned if condition_1 is true, else condition_2 is checked. value_2 is returned if condition_2 is true, else value_3 is returned.

Examples

1. Lambda function with if-else condition

In the following example program, we will write a lambda function that returns square of number if number is even, else cube of the number.

Python Program

x = lambda n: n**2 if n%2 == 0 else n**3

print(x(4))
print(x(3))

Output

16
27

2. Lambda function with nested if-else condition

We have already mentioned that we can write a nested if else inside lambda function.

In the following example program, we will write a lambda function that returns the number as is if divisible by 10, square of number if number is even, else cube of the number.

Python Program

x = lambda n: n if n%10 == 0 else ( n**2 if n%2 == 0 else n**3 )

print(x(4))
print(x(3))
print(x(10))

Output

16
27
10

Summary

Summarizing this tutorial of Python Examples, we learned how to use if else or nested if else in lambda function to conditionally return values.