Python
if-else
one-liner
conditional-statements
Python-tips

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

python
1age = 20
2
3# Multi-line
4if age >= 18:
5    status = "adult"
6else:
7    status = "minor"
8
9# One-liner (ternary expression)
10status = "adult" if age >= 18 else "minor"
11print(status)  # adult

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

python
1def get_label(score):
2    return "pass" if score >= 70 else "fail"
3
4print(get_label(85))  # pass
5print(get_label(60))  # fail
6
7# With multiple conditions (nested ternary)
8def get_grade(score):
9    return "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
10
11print(get_grade(95))  # A
12print(get_grade(72))  # C

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

python
1x = 10
2
3# Assignment
4result = x * 2 if x > 5 else x * 3
5print(result)  # 20
6
7# Inside print
8print(f"{'even' if x % 2 == 0 else 'odd'}")  # even
9
10# As function argument
11max_val = max(a if a > 0 else 0, b if b > 0 else 0)
12
13# In list comprehension
14numbers = [1, -2, 3, -4, 5]
15absolute = [n if n >= 0 else -n for n in numbers]
16print(absolute)  # [1, 2, 3, 4, 5]

If-Only (No Else) One-Liners

python
1# Single-line if statement (no else needed)
2x = 10
3if x > 5: print("big")
4
5# Multiple statements on one line (use semicolons)
6if x > 5: y = x * 2; print(y)
7
8# Short-circuit evaluation (for side effects)
9x > 5 and print("big")  # prints "big" if x > 5
10
11# Conditional function call
12data = get_data() if should_fetch else None

Single-line if without else is valid Python but discouraged in PEP 8 for anything beyond trivial statements.

Dictionary-Based Dispatch

python
1# Instead of nested ternary
2def get_day_type(day):
3    return {
4        'Monday': 'weekday',
5        'Tuesday': 'weekday',
6        'Saturday': 'weekend',
7        'Sunday': 'weekend',
8    }.get(day, 'weekday')
9
10# Or with a lambda map
11operation = {
12    '+': lambda a, b: a + b,
13    '-': lambda a, b: a - b,
14    '*': lambda a, b: a * b,
15}
16
17result = operation['+'](3, 4)  # 7

For multiple discrete conditions, dictionary lookup is cleaner and faster than chained ternary expressions.

Walrus Operator (Python 3.8+)

python
1# Compute and use a value in one line
2data = [1, 2, 3, 4, 5]
3
4# Without walrus — need two lines
5filtered = [x for x in data if x > 2]
6if filtered:
7    print(f"Found {len(filtered)} items")
8
9# With walrus — one expression
10if (n := len([x for x in data if x > 2])) > 0:
11    print(f"Found {n} items")

One-Liner Patterns Collection

python
1# Clamp a value to a range
2value = 150
3clamped = max(0, min(100, value))  # 100
4
5# Default value for None
6name = user_name if user_name is not None else "Anonymous"
7# Or more Pythonic:
8name = user_name or "Anonymous"  # Also catches empty string
9
10# Swap two variables
11a, b = b, a
12
13# Conditional list append
14result = [x for x in items if x > threshold]
15
16# First truthy value
17value = a or b or c or "default"

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. Use if user_name is not None for 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

Course illustration
Course illustration

All Rights Reserved.