Python Ternary Operator – 5 Ways To Implement Ternary Operators

1. Objective – Ternary Operator in Python

Today, we will see Python Ternary Operator. Moreover, we will discuss the example and syntax of Ternary Operator in Python. Also, we will learn before and nested Python Ternary Operators. At last, we will discuss ways for implementing Ternary operators in Python.
So, let’s start Python Ternary Operator.

Python Ternary Operator - Implementation With Example

Python Ternary Operator – Implementation With Example

2. Python Ternary Operator Example

Ternary operators in Python are terse conditional expressions. These are operators that test a condition and based on that, evaluate a value. This was made available since PEP 308 was approved and is available ever since version 2.4. This operator, if used properly, can reduce code size and enhance readability.
Do you know about Python Comparison Operator

a. Python if-else code

Let’s write code to compare two integers.

>>> a,b=2,3
>>> if a>b:
        print("a")
else:
        print("b")

b

b. Equivalent code with Ternary operator

So let’s try doing the same with ternary operators:

>>> a,b=2,3
>>> print("a" if a>b else "b")

b
Voila! Done in one line. Python first evaluates the condition. If true, it evaluates the first expression; otherwise, it evaluates the second. There is a lazy evaluation. It also evaluates the conditions left to right.
You must learn about Python Data Structures

3. The syntax for Python Ternary Operator

Now, let’s learn a little the syntax for Python Ternary Operator.

[on_true] if [expression] else [on_false]

In C++, it looks like this:

max=(a>b)?a:b

But this isn’t quite Pythonic, so Guido, Python’s BDFL (a status from which he has resigned permanently), rejected it. Another reason for the veto is that we already have many uses for the colon(:).
One more example of Python ternary Operators:

>>> from random import random
>>> a,b=random(),random()
>>> res="a" if a>b else "b"
>>> res

‘b’

>>> a,b

(0.009415785735741311, 0.9675879478005226)

4. Ways to Implement Ternary Operator

Below, we are discussing different ways of implementing Python Ternary Operator:

Python Ternary Operator

Ways to Implement Ternary Operator

a. Using Python Tuples

We can use tuples to specify what to do if the condition is True/False.
Before moving on, you must learn a little about Python Tuples

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

0.8182650892806171
This is equivalent to:

>>> (b,a)[True]

But we’re confused which this is- a or b. Let’s try tweaking this.

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

‘b:0.8182650892806171’
That’s more like it. Looking at the code, you’ll reckon the first argument in the tuple corresponds to a Boolean value of False; the second- True. This is because of False=0 and True=1. The condition resides within the [ ].
Note that this method evaluates both elements of the tuple, and hence is less efficient. This happens because it must first build the tuple before it can look for an index.

>>> condition=True
>>> 2 if condition else 1/0    #Follows the normal if-else logic tree

2

>>> (1/0,2)[condition]

Traceback (most recent call last):
File “<pyshell#48>”, line 1, in <module>
(1/0,2)[condition]
ZeroDivisionError: division by zero

b. Using Python Dictionaries

Likewise, we can make this happen using dictionaries with the same logic.
You must read about Python Dictionaries

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

‘a:0.37237928632774675’
Since we specify what to do when here, we can interchange the positions of key-value pairs.

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

‘a:0.37237928632774675’

c. Using Lambdas

We can also make use of Python Lambda Functions to act as a ternary operator.

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

‘b:0.5955717855531699’

5. Nested Python Ternary Operator

Let’s try chaining these operators, shall we?

>>> a=random()
>>> "Less than zero" if a<0 else "Between 0 and 1" if a>=0 and a<=1 else "Greater than one"

‘Between 0 and 1’
Have a look at Python Closure

>>> a

0.8537574133103878
Here, we check for the value of a. If it falls shorter than 0, we print “Less than zero”; if between 0 and 1, we print “Between 0 and 1”. Else, we print “Greater than one”. Notice how we nested them.

Python Interview Questions

6. Before Ternary Operators in Python

Before this was a thing with Python, this is what we did (we used a common idiom):

>>> a,b=2,3
>>> a<b and a or b

2
So how does this work? Let’s see.

  • a is 2 and b is 3
  • It checks if a<b
  • If true, it gives us True and a or b
  • This gives us a or b
  • It checks a
  • If false, it gives us False or b
  • This gives us b

This method, however, doesn’t work for a=0. This is because that would be True and 0 or b, which is True and False or b, which is False or b, which is b. Oops!
Now why don’t you try formulating an expression for a>b and try explaining it to yourself?
Let’s learn about Python Data Science
It could also be beneficial to use the and/or logic when one of our expressions is the same as the condition:

>>> def sayhello(): print('Hello')
>>> sayhello() if sayhello() else 'Bye'

Hello
Hello
True

>>> sayhello() or 'Bye'

Hello
True
So, this was all in Python Ternary Operator. Hope you like our explanation.

7. Conclusion – Python Ternary Operator

Phew! That’s all. Through this Python Ternary Operator blog, we tried our best to bring to you all there is to know about the ternary operator in Python. Moreover, we discussed the implementation of Ternary Operators in Python. Also, we saw Python Ternary Operators example and syntax. We curated our content from the best sources. Like this tutorial? If you’d like us to write about something that has to do with Python (and we haven’t already), please let us know in the comments below. We are excited to hear from you!
See also –
Python Bitwise Operator
For reference

1 Response

  1. black rosé says:

    Great tutorials so far been studying at my own space and also a great reference blog.
    Thanks

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.