Skip to content

Python Tenary Operator

diagram the ternary evaluates the condition first, then only one branch mermaid
Reading order and evaluation order differ, which is what makes it confusing at first: the condition sits in the middle but runs first. Only the branch that is chosen is evaluated at all, so an expensive or unsafe expression on the losing side never runs -- which is exactly what lets it guard against division by zero or a missing key.

The ternary operator, also known as the conditional expression, provides a concise and expressive way to write conditional statements in a single line. It’s a powerful tool for simplifying code and making it more readable. In this comprehensive guide, we’ll explore the ternary operator in Python, its syntax, use cases, and best practices.

The ternary operator is a conditional operator that returns a value based on the result of a condition. It’s a shorthand for the if-else statement. The ternary operator is also known as the conditional expression.

The ternary operator is a powerful tool for simplifying code and making it more readable. It’s a concise way to write conditional statements in a single line.

The ternary operator has the following syntax:

Syntax
<value_if_true> if <condition> else <value_if_false>

The ternary operator consists of three operands separated by the if and else keywords. The first operand is the condition, the second operand is the value to return if the condition is true, and the third operand is the value to return if the condition is false.

Let’s take a look at a simple example of the ternary operator in Python:

ternary_operator.py
# Ternary operator
x = 10
y = 5
z = x if x > y else y
print(z)

Output:

command
C:\Users\Your Name> python ternary_operator.py
10

In the above example, we have used the ternary operator to assign the value of x to the variable z if the condition x > y is true. Otherwise, the value of y is assigned to the variable z.

The ternary operator can be nested to create more complex conditional statements. The following example demonstrates how to use the nested ternary operator in Python:

nested_ternary_operator.py
# Nested ternary operator
x = 10
y = 5
z = 2
a = x if x > y else y if y > z else z
print(a)

Output:

command
C:\Users\Your Name> python nested_ternary_operator.py
10

In the above example, we have used the nested ternary operator to assign the value of x to the variable a if the condition x > y is true. Otherwise, the value of y is assigned to the variable a if the condition y > z is true. Otherwise, the value of z is assigned to the variable a.

The ternary operator is a shorthand for the if-else statement. It’s a concise way to write conditional statements in a single line. The ternary operator is a powerful tool for simplifying code and making it more readable.

Consider the following example:

if_else_statement.py
# if-else statement
x = 10
y = 5
if x > y:
    z = x
else:
    z = y
print(z)

Output:

command
C:\Users\Your Name> python if_else_statement.py
10

The above example can be rewritten using the ternary operator as follows:

ternary_operator.py
# Ternary operator
x = 10
y = 5
z = x if x > y else y
print(z)

Output:

command
C:\Users\Your Name> python ternary_operator.py
10

As you can see, the ternary operator is a concise way to write conditional statements in a single line.

The ternary operator enhances code readability by succinctly expressing conditional statements in a single line. It’s especially useful for simple conditions.

The ternary operator helps avoid redundancy when assigning values based on conditions, eliminating the need for repetitive if-else blocks.

While the ternary operator is powerful for simple conditions, it’s essential to use it judiciously. For complex conditions, especially those involving multiple operations, an if-else block might be more readable.

The Python Enhancement Proposal (PEP) 8, the style guide for Python code, recommends using the ternary operator sparingly, especially when it makes the code less readable. Clarity should be prioritized over brevity.

The ternary operator in Python is a valuable tool for writing concise and readable code, especially in cases where simple conditional assignments are needed. As you incorporate the ternary operator into your code, keep in mind the balance between brevity and readability. Use it for straightforward conditions to enhance the clarity of your code, and be mindful of PEP 8 guidelines for maintaining a consistent and readable coding style.

For more insights and practical examples, check out our tutorials on Python Central Hub!


sketch The condition is in the middle but runs first p5.js
Reading order and evaluation order differ, which is the whole reason this looks odd at first. The condition is evaluated first, and then exactly one branch runs -- the other is never touched. That is what lets a ternary guard against a division by zero or a missing key, rather than merely hiding one.
pch.quizTag pch.quizDefaultTitle
  1. In `a if cond else b`, what is evaluated first?

    pch.quizShowAnswer

    B — `cond` — The condition runs first even though it is written in the middle. Only the chosen branch is then evaluated — the other is never touched.

  2. Is `x / y if y else 0` safe when `y` is 0?

    pch.quizShowAnswer

    B — Yes — the division is never evaluated when the condition is falsy — Exactly the point of the construct. Because the losing branch is not evaluated, an unsafe expression there is never executed.

  3. Why can a ternary appear inside an f-string or a comprehension, when `if`/`else` cannot?

    pch.quizShowAnswer

    B — It is an EXPRESSION, so it produces a value — Statements do not produce values and cannot be embedded. That also means a ternary cannot contain `return`, `raise` or an assignment.

  4. When should you NOT use a ternary?

    pch.quizShowAnswer

    B — When it is nested more than once and no longer reads as a sentence — Nested ternaries are where the readability benefit reverses. If you cannot read it aloud in one go, an `if` statement is clearer.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading