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.


[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:

b. Using ternary operator

>>> x, y = 5, 6
>>> print("x" if x> y else "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)

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]

Above is equivalent to -

>>> (b, a) [True]

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. Using Python dictionaries

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

We can interchange the key-value pair -

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

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]()

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"


'between 0 and 5'

Let’s check the actual value of x -

>>> x

Updated on: 30-Jul-2019

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started