Python Ternary Operator: Syntax and Practical Use
Learn how to use Python's conditional expression (the ternary operator) for concise value selection, including syntax, common mistakes, and when a regular if-else is clearer.

The Python ternary operator, formally called a conditional expression, lets you choose between two values based on a condition in a single line. The syntax is value_if_true if condition else value_if_false. It is not a unique operator like ? : in other languages; it uses the keywords if and else in a specific order. This expression is evaluated lazily: only the selected branch is executed, so side effects in the other branch do not occur.
The Basic Syntax of the Python Ternary Operator
The conditional expression has three parts: the condition, the value when the condition is true, and the value when it is false. The order is important: the true value comes first, then the condition, then the else keyword and the false value. For example:
age = 20
status = "adult" if age >= 18 else "minor"Here, status becomes "adult" because the condition is true. The expression reads naturally as "adult" if age >= 18 else "minor". This order is a common source of confusion for developers coming from C or Java, where the condition comes first. In Python, you write the result for the true case before the condition.
Using the Ternary Operator in Assignments
The most common use is assigning a value to a variable based on a condition. It replaces a short if-else block:
if price > 100:
discount = 0.1
else:
discount = 0.05The same logic becomes:
discount = 0.1 if price > 100 else 0.05This is concise, but it is only appropriate when both branches are simple expressions. If either branch requires multiple statements or complex logic, a regular if-else block is clearer. The ternary operator is an expression, not a statement, so it can be used anywhere an expression is allowed, such as in function arguments, list comprehensions, or return statements.
Nesting Conditional Expressions
You can nest conditional expressions, but readability degrades quickly. For example:
result = "high" if score > 90 else "medium" if score > 70 else "low"This works because the conditional expression is right-associative. The expression is evaluated as "high" if score > 90 else ("medium" if score > 70 else "low"). While this avoids multiple lines, it becomes hard to follow when the logic is more complex. Most developers prefer a function or a dictionary mapping for multi-level conditions. Nesting is acceptable for a simple two-level decision, but beyond that, the code becomes difficult to maintain.
Common Mistakes and How to Avoid Them
A frequent mistake is reversing the order of the true and false values. Because the condition appears in the middle, it is easy to write condition if true_value else false_value by accident. The interpreter will not raise an error; the expression is valid but means something different. For example, this line looks like a direct translation of the C-style expression age >= 18 ? "adult" : "minor":
# Wrong: this does not do what it looks like
value = age >= 18 if "adult" else "minor"Python parses it as (age >= 18) if "adult" else "minor": the condition is "adult", and because that string is truthy, the expression returns age >= 18 (a boolean), not "adult" or "minor". The correct form is "adult" if age >= 18 else "minor".
Another mistake is using the ternary operator with statements that have side effects. Since only the selected branch is evaluated, the other branch's side effects are skipped. This is usually desired, but if you expect both branches to execute some code, you need a regular if-else. Also, the ternary operator has lower precedence than most operators, so parentheses may be needed when combining with arithmetic or logical operations. For instance, x + 1 if condition else y is parsed as (x + 1) if condition else y, which is fine, but x if condition else y + 1 is parsed as x if condition else (y + 1). If you need to add something to the whole expression, wrap it in parentheses.
Readability and Maintainability Considerations
The ternary operator can improve readability when used for a simple, direct mapping between a condition and two short values. It keeps the logic on one line, reducing vertical space. However, it can harm readability when the condition is long, the values are complex expressions, or the expression is nested. A general guideline is to use it only when the entire expression fits comfortably on one line and the condition is easy to understand at a glance. If you find yourself adding parentheses or breaking lines, a regular if-else block is likely clearer.
When to Prefer if-else Over the Ternary Operator
There are situations where a regular if-else is the better choice. If you need to assign different variables, perform multiple operations, or handle exceptions, the ternary operator is not suitable. For example, if you need to log something in one branch and return a value in another, you cannot do that with a conditional expression. Also, if the condition is complex, such as a long expression with multiple and and or operators, an if-else statement with a well-named variable for the condition is more readable. The ternary operator is best for simple, inline value selection.
Performance Characteristics and Runtime Behavior
From a runtime perspective, the ternary operator does not provide a meaningful performance advantage over an equivalent if-else statement; the choice is about code clarity. Because the conditional expression is lazy, it can be useful when the fallback value is expensive to compute and you want to avoid it when the condition is true. For example, data.get(key) if key in data else compute_default() avoids calling compute_default() when key is present, whereas data.get(key, compute_default()) would evaluate the argument eagerly. The lazy evaluation is a behavior to be aware of, but it is rarely a performance optimization in ordinary code. In general, do not choose the ternary operator for performance reasons; choose it for conciseness when it improves readability.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.