Codectionary / Developer documentation / Python

Conditional (Ternary) Expression

A conditional expression chooses one of two values: value_if_true if condition else value_if_false. It is an expression, so it can appear in an assignment, a return statement or a function argument. Use an if statement when the branches perform several actions.

How it works

Python evaluates the condition first, even though it appears in the middle. It evaluates only the selected branch. This permits a guarded expression such as total / count if count else 0 when zero is the intended fallback.

Both result branches are required. They may produce different types, but consistent types usually make later code easier to understand. A conditional expression does not introduce a new scope.

In a comprehension, a conditional expression transforms each item, while a trailing if filters items out. The labels example keeps every number and chooses one label for each.

Common mistakes and boundaries

Avoid nested conditional expressions for multi-step decisions; an if/elif/else statement is easier to inspect.

Do not replace a conditional expression with condition and a or b: that selects b when a is falsy, even when the condition was true.

Try it yourself

Label each number in [0, 1, 2] as zero or nonzero while preserving all three entries. Then write a separate comprehension that removes zero, and compare the list lengths.

Syntax

value_if_true if condition else value_if_false

Examples

Basic Ternary Expression

Assigning one of two values based on a condition, without a full if/else block.

age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

# Equivalent full if/else
if age >= 18:
    status = "adult"
else:
    status = "minor"
  1. The condition is true, so adult is assigned. The full if/else below demonstrates the same choice without printing a second time.
  2. Expected output: adult

Ternary in a Function Call

Using a ternary expression directly as an argument.

def display(message, uppercase):
    print(message.upper() if uppercase else message)

display("hello", True)   # HELLO
display("hello", False)  # hello
  1. Only the chosen expression is evaluated. The first call transforms the message; the second prints it unchanged.
  2. Expected output: HELLO hello

Ternary Inside a List Comprehension

Combining a ternary expression with a comprehension to transform items conditionally.

numbers = [1, 2, 3, 4, 5, 6]

labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd', 'even']
  1. The conditional chooses a label for each number rather than filtering numbers out, so six inputs produce six labels.
  2. Expected output: ['odd', 'even', 'odd', 'even', 'odd', 'even']

Best practices

  • Use the ternary expression for simple, single-value choices - fall back to a full if/else statement once logic gets more involved
  • Avoid nesting ternary expressions within each other; it quickly becomes hard to read (prefer if/elif/else instead)
  • Ternary expressions are great inside list comprehensions and default argument values where a full if/else statement is not possible
  • Remember the order reads 'result if condition else alternative', which can feel backward compared to other languages

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading