Learn Python Ternary Operator With Examples

Python is notorious for one-liners. You can write an entire for loop in a single line using list comprehension, swap variables, and the list goes on. Moreover, in comparison to other high-level languages, python code is the most concise and readable. Python has another one-liner called the ternary operator for conditional computing statements.

Ternary operator working
Ternary operator syntax in C or Java.

Have a look at the image above. Does it feel familiar? If yes, you might have worked with it in other languages like C or Java or any different language. If not, then don’t worry. We will go through its working. However, first, we will look at traditional conditional statements.

age = int(input("Enter your age:"))

if age <= 10:
    print("Sorry! you can't ride the rollercoaster.")
else:
    print("You may pass!")
The output of the if-else conditional example
The output of the if-else conditional example

Python’s Ternary Operator

As the name implies, ternary contains three operands. One is the condition that gets evaluated first. And then the condition short circuits to either true or false accordingly.

Ternary operator working
Ternary operator working

Syntax

The ternary operator was non-existent before version 2.5. Besides, python’s ternary operator’s syntax is a little different from other languages. Python’s ternary operator doesn’t have ‘ ? ‘ and ‘ : ‘. Instead, it uses if-else keywords. Look at the syntax below:

if_true if condition else if_false

Now let’s try to write down the if-else code in the introduction using the ternary operator.

age = int(input("Enter your age:"))
print("Sorry! you can't ride the rollercoaster." if age <= 10 else "You may pass!")
One-liner solution using ternary operator
One-liner solution using ternary operator

Examples of Python’s ternary operator

Let’s look at some examples of the ternary operator to consolidate our understanding.

Example 1:

Checking the greatest of two numbers.

num1, num2 = map(int,input("Enter two numbers:").split())

def get_greatest(num1, num2):
    print(f"{number1} greater than {num2}" if num1 > num2 else f"{num2} greater than {num1}")
    
get_greatest(num1,num2)
Greatest of two numbers using ternary operator.
Greatest of two numbers using ternary operator.

Example 2: Nesting in ternary operator

I am checking the greatest of three numbers.

num1, num2, num3 = map(int,input("Enter two numbers:").split())

def get_greatest(num1,num2,num3):
    return (num1 if num1 > num3 else num3) if num1 > num2 else (num2 if num2 > num3 else num3)

print(get_greatest(num1,num2,num3))
Greatest of three numbers using ternary operator.
Greatest of three numbers using ternary operator.

Alternative to ternary operators

Python’s Tuple ternary operator

Python has yet another way to use ternary operator-like functionality. Although, this method isn’t used much and has a disadvantage to it. Let’s discuss its syntax, work through some examples, and compare it to the regular python ternary operator.

Syntax:

(if_condition_is_false, if_condition_is_true)[condition]

Examples:

Example 1:
greet = True
greet_person = ('Hi', 'Bye')[greet]
print(f'{greet_person}, Jiraya.')
Ternary tuple example 1
Ternary tuple example 1

As a matter of fact, the tuple operator feels similar to a regular python ternary operator. However, its inner working is quite the opposite. For instance, let’s take an example to clarify this distinction.

print((1/0, 2)[True])

If you try to run the following code, the expected outcome should be ‘ 2 ‘. However, instead, we get a zero division error. This is because it evaluates both the expressions, unlike a regular python ternary operator, which short circuits to either expression.

The tuple ternary operator evaluates both the expression
The tuple ternary operator evaluates both the expression

Python’s List ternary operator

Like the tuple ternary operator, you can also use a list in place of a tuple. Let’s look at an example.

greet = False
greet_person = [‘Hi’, ‘Bye’][greet]
print(f'{greet_person}, Jiraya.’)

List ternary operator
List ternary operator

Python’s Dictionary ternary operator

Let’s look at an example of how can we can use it. For instance:

d = {'Yuji':15,'Megumi':15,'Nobara':16,'Gojo':28,'Geto':27}

key = 'Gojo'
age = d[key] if key in d else None
print(age)

key = 'Yuta'
age = d[key] if key in d else None
print(age)
Dictionary Ternary Operator with Membership
Dictionary Ternary Operator with Membership

Ternary operator with lambda

Lambda or anonymous functions too can be used with the ternary operator in Python. We can apply conditions on the ternary operator, for instance:

discount = lambda price: price*0.1 if price > 1000 else price*0.02
print(discount(10000))
print(discount(120))

The code above applies a discount to an item purchased if its price range is greater or less than 1000. When the price is more significant than 1000, a discount of 10% is applied, while for item prices less than 1000, only a 2% discount is added.

Lambda function used in ternary operator
Lambda function used in ternary operator

Ternary operator assignment multiple lines

You can assign logical lines into multiple physical lines using the parenthesis, square brackets, or even curly braces. Splitting expressions or lines of code into multiple physical lines is termed implicit line joining. Let’s look at an example:

The above

age = int(input("Enter Age: "))
vote_or_not = ["You are of legal to vote" if age >= 18 
else "You aren't of legal age to vote."]
print(vote_or_not)
Ternary operator on multiple lines
The ternary operator on multiple lines

Precedence of the ternary operator

Ternary operators or conditional expressions have low precedence. However, when used inside the parenthesis, square brackets, or curly braces, its precedence should increase.

Ternary operator without else in Python

While the regular ternary operator doesn’t support operation, moreover, it will throw an invalid syntax error if you try to do so. To demonstrate, we have commented on the else part of the ternary operator.

l = ['junji ito','naoki urasawa','hiromu arakawa']
name = input("Enter name: ")
l.append(name if len(l) > 0)
Syntax error gets thrown
Syntax error gets thrown.

If you try to run the program, a syntax error will be thrown, as shown in the image above.

So what is the workaround to this problem? Long story short, the ternary operator doesn’t have such functionality. Therefore, we will use a logical operator and a condition. For instance:

l = ['junji ito','naoki urasawa','hiromu arakawa']
name = input("Enter name: ")
len(l) > 0 and l.append(name)
print(l)

We have to use the following syntax:

<condition> and <some operation>

So, and operator evaluates the proper side operation only if the condition is true. However, if the condition turned to be false, it won’t be operated.

Using and operator with a condition.
Using and operator with a condition.

FAQs on Python Ternary Operator

Ternary operator syntax in Python?

if_true if condition else if_false

Does Python have a ternary operator?

The ternary operator was introduced in python version 2.5. However, its syntax is different from other programming languages.

Can we do short-circuiting in the ternary operator?

Ternary operator automatically does short-circuiting. Ternary contains three operands. One is the condition that gets evaluated first. As a result, the condition short circuits to either true or false accordingly.

Can we do a null ternary check?

Yes, we can do a null ternary check using shorthand ternary. For instance:
value = None
msg = value or "Value is None"
print(msg)

Output: Value is None

Conclusion

The following article covered Python’s ternary operator. We looked at how it is different when compared to other programming languages’ ternary operators. Moreover, we also tried to understand its functioning using some examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments