Ternary Operator Without Else In Python

In this tutorial, we are going to learn about implementing a ternary operator without else in Python. Firstly, let us know about ternary operators.

Ternary Operators:-

To learn more click: Ternary Operator in Python. Python versions 2.5 or later supports ternary operators. Because it was added in Python 2.5. Ternary operators allow testing a condition in a single line. It replaces the multiline if-else conditions by making the code compact.

Syntax:

[on true] if [expression] else [on false]

Example:-

x, y = 'a', 'b'
res = x if x<y else y
print(res)

Output:-

a

As a result, we get ‘a’ as output. Because, if the condition is true then it prints the expression before it. If the condition is false then it prints the condition after else keyword. Now let us see how to implement a ternary operator without else keyword.

Implementing ternary operator without else keyword:-

Similarly, we can also implement it without else keyword but with the help of any of the following:- Dictionaries, or lambda function. Let’s see how to implement it.

Implementing with Dictionaries:-

Example:-

x, y = 'a', 'b'
print({True:x, False:y} [x < y])

Output:-

a

In the above code if the condition in the print statement is true it will print the value of the True key in the dictionary. If the condition is false then it will print the value of the False key in the dictionary. So, as a result, we get ‘a’ as output.

Implementing with Lambda Function:-

Example:-

x, y = 'a', 'b'
print((lambda: y, lambda: x)[x<y]())

Output:-

a

In the above code if the condition in the function is true it executes the 2nd lambda function. If the condition is false then it executes the first lambda function.

Leave a Reply

Your email address will not be published. Required fields are marked *