What is Python Ternary Operator?

Python ternary operators are terse conditional expressions. These are operators that check a condition and then assess a value in light of that. This has been accessible ever since PEP 308 was authorized and is now in version 2.4. If used correctly, this operator may make code smaller and easier to comprehend.

1. Python if-else code

Let’s write code to compare two integers.

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

Output

b

2. Equivalent code with Ternary operator

Let’s try using the same strategy for ternary operators:

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

Output

b

The syntax for Python Ternary Operator

Let’s learn a little about the syntax for Python Ternary Operator.

[on_true] if [expression] else [on_false]

In C++, it looks like this:

max=(a>b)?a:b

Ways to implement the ternary operator

Below, we discuss different ways to implement the Tertiary Operator in Python:

Python ternary operator

1. Using Python Tuples

To indicate what to do if the condition is True or False, we may use tuples.

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

Output

0.8182650892806171

This is comparable to:

>>> (b,a)[True]

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

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

Output

‘b:0.8182650892806171’

That’s better, I think. By examining the code, you may determine that the first parameter in the tuple represents a Boolean value of False and the second, a value of True. Because False=0 and True=1, this occurs. The condition resides within the [ ]. Be aware that this approach is less effective since it examines both components of the tuple. This occurs as a result of the fact that it must construct the tuple before looking for an index.

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

Output

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

Output

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

2. Using Python Dictionaries

Similarly, by applying dictionaries with the same logic, we may do this.

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

Output

‘a:0.37237928632774675’

We can swap the placements of key-value pairs since we have specified what to do when here.

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

Output

‘a:0.37237928632774675’

3. Using Lambdas

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

Output

‘b:0.5955717855531699’

Nested Python Ternary Operator

The nested ternary operator evaluates its conditions in what order?

Short Answer: The nested ternary operator '1' if x else '2' if y else '3' evaluates the condition from left to right, i.e., '1' if x else ('2' if y else '3'). In short, first condition first!

Python ternary operator

Problem Formulation

Given a nested ternary operator in Python:

'1' if x else '2' if y else '3'

What is the nested ternary operator’s operator precedence?

  • Scenario A('1' if x else '2') if y else '3'
  • Scenario B'1' if x else ('2' if y else '3')

Scenario A is semantically different from Scenario B as can be seen in this example:

>>> x, y = True, False
>>> # Scenario A
>>> ('1' if x else '2') if y else '3'
'3'
>>> # Scenario B
>>> '1' if x else ('2' if y else '3')
'1'

Simple Nesting

From left to right evaluation is used by the ternary operator. If the ternary operator is nested, Python first evaluates the left condition before it evaluates the right condition.

>>> x, y = True, False

# Scenario A
>>> ('1' if x else '2') if y else '3'
'3'

# Scenario B
>>> '1' if x else ('2' if y else '3')
'1'

# Correct Scenario: B
>>> '1' if x else '2' if y else '3'
'1'

Multiple Nesting

What if the ternary operator has several layers of nesting:

'1' if x else '2' if y else '3' if z else '4'

The ternary operator once more computes from left to right. Such as in ‘1’ if x else ‘2’ if y else ‘3’ if z else ‘4’, Python first examines the left condition before it analyzes the second-left condition before it evaluates the third-left condition, even if the ternary operator contains more than two nesting levels.

Example:

>>> x, y, z = True, True, False

>>> # Scenario A
>>> (('1' if x else '2') if y else '3') if z else '4'
'4'

>>> # Scenario B
>>> '1' if x else ('2' if y else ('3' if z else '4'))
'1'

>>> # Correct Scenario: B
>>> '1' if x else '2' if y else '3' if z else '4'
'1'

Before Ternary Operators in Python

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

Output

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

But, when a=0, this approach fails. 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. Why don’t you now attempt to create an expression for the relation a>b and try to justify it to yourself?

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'

Output

Hello
Hello
True
>>> sayhello() or 'Bye'

Output

Hello
True

Conclusion

We have provided you with all the information there is to know about the Python ternary operator in this blog. Furthermore, we discussed the implementation of the Tertiary Operator in Python.

By integrating reputable platforms like Magento eCommerce, BigCommerce, and Shopify, ONEXT DIGITAL provides top-notch eCommerce development services. With a trained team of specialists and engineers, we can overcome any e-commerce challenge, from deployment to migration.
If you’d like us to write about something that has to do with Python, please let us know in the comments below. We are excited to hear from you!

Read more>>>

Nameerror Name Is Not Defined Python: What’s It And How To Solve This