Ternary Operator in Python

We all are familiar with the conditional if-else expressions so far. In this tutorial, we will learn about the shortening of the if-else ladder with the help of the ternary operator.

Ternary Operator in Python to shorten the if-else

They tend to evaluate something based on the test conditions being true or false (Boolean values).
It offers inline code writing by replacement of multi-line if-else ladder enhancing the compactness and clarity.

The syntax of ternary operator in Python

<expression to be evaluated> if <test condition> else <expression to be evaluated>

In assignment expression – Ternary

# conditional statements
y, z = 10, 29
  
# Copy value of y-z in diff if y > z else copy z-y 
diff = y-z if y > z else z-y 
  
print diff
Output:
>>>19

As test condition evaluates to be true the value of a-b is printed and b-a is not evaluated.

Lambda, Tuple & Dictionary Data type – Ternary in Python

# Python program to demonstrate ternary operator 
a, b = 7, 29

# Use tuple for selecting an item 
print( (a,b) [a < b] ) #(display when false,display when true)

# Use Dictionary for selecting an item 
print({True: a, False: b} [a < b])  
# the last expression of true and false are used for the result 
print({True: a, False: b,True: a+b} [a < b])

print((lambda: b, lambda: a,lambda: a+b)[a < b]()) #(display when false,display when true) 
#in case extra arguments are provided there is no effect
print((lambda: b-a, lambda: a,lambda: a+b)[b < a]()) #last expression is not evaluated 
# lamda is more efficient here
# because in lambda expression  
# only one expression will be evaluated 
Output:
29
7
36
7
22

Points to remember for ternary operator in Python

1. while setting up the test condition all test cases must be kept in mind.
2. when implementing a tuple data type first expression is evaluated when test condition is false and second when it becomes true.
3. while using the dictionary type key can have only two values i.e. Boolean True & False.
4. During the use of lambda expression only first to argument are evaluated in order of false -> true.



Also learn,

Leave a Reply

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