Does Python have a ternary conditional operator

Hello everyone. In this post, we are going to learn about the ternary conditional operator in Python. Before starting we have a question, does Python have this operator? The answer is yes!. This specific operator in Python came into existence in version 2.5.

Ternary Operator: It is an operator that takes three arguments. First is condition argument, second is the result of true condition and third is the result of the false condition.

Let’s begin the tutorial with some examples.

Also read: Membership and Identity Operator in Python

The ternary operator in Python

In Python ternary operator is a shortened form of else-if ladder making the program more robust. Rather than using lines of the else-if ladder, it is more compact to use the ternary operator in place of it. See the example below.

Syntax

[value on true] if [condition] else [value on false]
x,y=10,20
max= x if x>y else y
print(max)

Output:

20

The condition(10>20) is false therefore the value of y is assigned to the max and printed.

The same can be implemented using the tuple, dictionary, and lambda.

Tuple, dictionary, and lambda as the ternary operator

Look at the code below before we discuss:

#Tuple as ternary operator
max=((y,x)[x>y])
print(max)
# Dictionary as ternary operator
print({True: x, False: y} [x > y])

#lambda as teranay operator
print((lambda:y,lambda:x)[x>y]())
#On true x is returned and on false y is returned

In the above code, we have used the tuple, dictionary and lamda as the ternary operator. The code contains each example accordingly.

The output is given below for this program:

20
20
20
20

I hope you understood it well. Please comment below if you find anything incorrect in this post. For a tutorial on any other topic of Python, comment below the topic name.

Also read: Find common elements from two tuples in Python

Thank You.

 

 

Leave a Reply

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