How to condense if/else into one line in Python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python's ternary (conditional) expression value_if_true if condition else value_if_false condenses an if/else block into a single line. Unlike C-style condition ? a : b, Python places the condition in the middle. This works for assignment, return statements, function arguments, and list comprehensions. For if-only (no else), use a single-line if statement or short-circuit evaluation. This article covers all one-liner patterns with readability guidelines.
Ternary Expression
The ternary expression is an expression, not a statement — it returns a value and can be used anywhere a value is expected.
In Function Returns
Nested ternary expressions work but reduce readability. For more than two branches, a dictionary or regular if/elif/else is clearer.
In Assignments and Expressions
If-Only (No Else) One-Liners
Single-line if without else is valid Python but discouraged in PEP 8 for anything beyond trivial statements.
Dictionary-Based Dispatch
For multiple discrete conditions, dictionary lookup is cleaner and faster than chained ternary expressions.
Walrus Operator (Python 3.8+)
One-Liner Patterns Collection
Common Pitfalls
- Nested ternary is hard to read:
"A" if x > 90 else "B" if x > 80 else "C" if x > 70 else "F"is valid but confusing. Use if/elif/else or a dictionary for more than two branches. - Ternary is an expression, not a statement: You cannot use
if x: do_thing() else: do_other()as a ternary. The ternary form requires values on both sides:result = a if cond else b. - or short-circuit treats falsy values as missing:
name = user_name or "Anonymous"replaces empty strings, zero, and False with the default, not just None. Useif user_name is not Nonefor None-only checks. - Side effects in ternary expressions:
print("yes") if condition else print("no")works but is discouraged. Ternary expressions should return values, not perform actions. - PEP 8 discourages compound statements:
if x > 5: print(x)on one line is valid but PEP 8 recommends the two-line form for clarity. One-liners are acceptable for simple, obvious conditions only.
Summary
- Python ternary syntax:
value_if_true if condition else value_if_false - Use for simple two-way assignments, returns, and expressions
- For if-only (no else), use single-line
if condition: action - Avoid nested ternary for more than two branches — use dict lookup or if/elif/else
- The walrus operator
:=(Python 3.8+) enables assign-and-test in one expression - Prioritize readability — a clear two-line if/else is better than a confusing one-liner

