Ternary Operator in Python?


Many programming languages support ternary operator, which basically define a conditional expression.

Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.

Syntax

[on_true] if [expression] else [on_false]

Let’s write one simple program, which compare two integers -

a. Using python if-else statement -

>>> x, y = 5, 6
>>> if x>y:
   print("x")
else:
   print("y")
y

b. Using ternary operator

>>> x, y = 5, 6
>>> print("x" if x> y else "y")
y

With ternary operator, we are able to write code in one line. So python basically first evaluates the condition, if true – evaluate the first expression else evaluates the second condition.

>>> def find_max(a,b):
return a if (a>b) else b
>>> find_max(5, 6)
6

Way to implement Ternary Operator

Below are different ways to implement ternary operator.

a. Using Python Tuples

>>> a, b = random(), random()
>>> (b, a) [a>b]
0.5497848117028667

Above is equivalent to -

>>> (b, a) [True]
0.5065247098746795

But if you are confused with value returned is of ‘a’ or ‘b’. Let’ rewrite above code.

>>> (f"b:{b}", f"a:{a}") [a>b]
'b:0.5497848117028667'

b. Using Python dictionaries

>>> a, b = random(), random()
>>> {False: f"b:{b}", True: f"a:{a}"}[a>b]
'a:0.8089581560973976'

We can interchange the key-value pair -

>>> {True: f"a:{a}", False: f"b:{b}"}[a>b]
'a:0.8089581560973976'

c. Using Lambdas

We can use python lambda function to act as a ternary operator -

>>> (lambda: f"a:{a}", lambda: f"b:{b}")[a>b]()
'b:0.6780078581465793'

Nested Python ternary operator

Let’s try chaining these operators -

>>> from random import random
>>> x = random()
>>> "Less than zero" if x<0 else "between 0 and 5" if a>=0 and a<=5 else "Greather than five"

Output

'between 0 and 5'

Let’s check the actual value of x -

>>> x
0.08009251123993566

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements