How to condense if/else into one line in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
Related reading
- How to configure Celery to run as systemd service with a Django application served by Gunicorn?
- How to connect kafka topic with web endpoint using Faust Python package?
- How to connect pika to rabbitMQ remote server? (python, pika)
- How to connect to Cassandra inside a Pylons app?
- How to connect to the centralized MySQL database from my django website?
- How to construct a set out of list items in python?
- How to consume messages in last N days using confluent-kafka-python?
- How to consume RabbitMQ messages via pika for some limited time?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.