a if cond else b

Python puts the condition in the MIDDLE, unlike almost every other language. The else branch is mandatory — there is no one-sided form.

Conditional operatorPython 2.5+Live demo
Common call
x if cond else y
Returns
one of the two values; the other is never evaluated
Replaces
a four-line if/else that only assigns a variable
Watch out
else is required, and the condition sits in the middle, not first
value_if_truevalue_if_true — Result when the condition is truthy. Evaluated only in that case.type: Any · required if conditioncondition — Tested for truthiness, not for equality to True. 0, empty containers and None are falsy.type: Any · required else value_if_falsevalue_if_false — Result when the condition is falsy. Mandatory — there is no if-without-else form.type: Any · required
→ Any

Demo

Live evaluation
Try:
Inputs
aAnyvalue when true
condintcondition (0 is falsy)
bAnyvalue when false
Output
'yes' if 1 else 'no'
'yes'

The condition sits between the two results, which is what makes Python read like English — "yes if the flag else no". Note that it tests TRUTHINESS, not equality with True: 42 and -1 are both truthy, and only 0 selects the else branch. In real Python the branch that is not chosen is never evaluated at all, which matters when one side would raise or is expensive.

Operands

NameTypeRequiredDescription
value_if_trueAnyyesResult when the condition is truthy. Evaluated only in that case.
conditionAnyyesTested for truthiness, not for equality to True. 0, empty containers and None are falsy.
value_if_falseAnyyesResult when the condition is falsy. Mandatory — there is no if-without-else form.

Return value

Any — The first operand when the condition is truthy, otherwise the third. Only the branch that is chosen gets evaluated.

Common patterns

Conditional assignment
The main use — collapses a four-line if/else that only sets a name.
label = "even" if n % 2 == 0 else "odd"
Guard against a bad value inline
The unevaluated branch is what makes this safe.
ratio = total / count if count else 0
Inside a comprehension
Transforms each item; note this is not the same as a filtering if.
[x if x > 0 else 0 for x in values]

Examples

1. Truthy
'yes' if 1 else 'no'
Returns
'yes'
2. Falsy
'yes' if 0 else 'no'
Returns
'no'
3. Empty is falsy
'full' if [] else 'empty'
Returns
'empty'
4. Safe division
10 / 2 if 2 else 0
Returns
5.0
5. Lazy — no error
1 / 0 if False else "safe"
Returns
'safe'
6. Chained
'neg' if -1 < 0 else 'zero' if -1 == 0 else 'pos'
Returns
'neg'

Pitfalls

1. else is mandatory
There is no one-sided conditional expression. Omitting else is a SyntaxError, because an expression must always produce a value.
No value for the false case
x = 'yes' if cond
SyntaxError: expected 'else' after 'if' expression
Supply both
x = 'yes' if cond else None
valid
2. The filtering if in a comprehension is a different thing
A trailing if FILTERS items out; a leading conditional expression TRANSFORMS every item. Their positions differ and so do their results, which makes this a persistent source of confusion.
Transforms, keeps all
[x if x > 2 else 0 for x in [1, 2, 3]]
[0, 0, 3]
Filters, drops some
[x for x in [1, 2, 3] if x > 2]
[3]
3. Chaining gets unreadable fast
Nested conditional expressions are legal and right-associative, but two levels is already hard to scan. A dict lookup or a plain if/elif chain communicates far better.
Hard to follow
s = 'a' if n == 1 else 'b' if n == 2 else 'c' if n == 3 else 'd'
legal, unreadable
Use a mapping
s = {1: 'a', 2: 'b', 3: 'c'}.get(n, 'd')
clearer
4. It binds loosely — parenthesise in bigger expressions
The conditional has very low precedence, so surrounding operators grab their operands first. Concatenation and arithmetic around an unparenthesised ternary rarely mean what they look like.
Binds unexpectedly
'a' + 'b' if False else 'c'
'c' # the + applies to the true branch
Parenthesise
'a' + ('b' if False else 'c')
'ac'

When to use

Use it
  • Choosing between two values in an assignment
  • Supplying a default inline without a full if/else block
  • Transforming items inside a comprehension
  • Argument values that depend on one condition
Reach for something else
  • More than one level of nesting → if/elif or a dict lookup
  • Either branch needs statements → a real if block
  • Only one branch matters → a plain if, or the or idiom for defaults

Notes

Complexity
O(1) plus whatever the chosen branch costs; the other branch is never evaluated
Return
Whichever operand was selected — no conversion is applied
CPython impl
Compiled to a conditional jump; there is no __ternary__ hook to override
Memory
No allocation of its own
Thread-safe
Yes — evaluation order is well defined

FAQ

PEP 308 chose the ordering to read as English — "the result, if the condition, otherwise the other". It puts the common case first, which is the opposite of the C-style cond ? a : b that most other languages use.

status = 'on' if enabled else 'off'

History

2.5
Conditional expressions added by PEP 308, after long debate over the syntax.