Ternary Operator using Python Lambda
In Python, lambda functions are used when we have only one expression to evaluate. Hence using the teranery operator with lambda makes it quite simple and easy. It works exactly like the tuple. That is we declare the False and True values at index 0 and 1 respectively.
Syntax: (lambda: false_value, lambda: true_value) [condition] ()
Example: In this example, we are using Lambda to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.
# Python program to demonstrate ternary operator
a = 10
b = 20
print((lambda: "b is minimum", lambda: "a is minimum")[a < b]())
Output:
a is minimum
Ternary Operator in Python
In Python, Ternary Operator determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.
It’s convenient when we want to avoid writing multiple lines for a simple if-else condition. Like in simple if-else, the first option, the true_value will be executed when the condition provided in the expression is True. If the condition returns False, then false_value will be executed.
Syntax: true_value if condition else false_value
The ternary operator can be used in various ways. Let us see a few different examples to use Ternary Operators in Python:
Table of Content
- Python Ternary If Else
- Ternary Operator in Nested If else
- Ternary Operator using Python Tuple
- Ternary Operator using Python Dictionary
- Ternary Operator using Python Lambda
- Ternary Operator with Print Function
- Limitations of Python Ternary Operator