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.
Demo
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
| Name | Type | Required | Description |
|---|---|---|---|
| value_if_true | Any | yes | Result when the condition is truthy. Evaluated only in that case. |
| condition | Any | yes | Tested for truthiness, not for equality to True. 0, empty containers and None are falsy. |
| value_if_false | Any | yes | Result 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
label = "even" if n % 2 == 0 else "odd"
ratio = total / count if count else 0
[x if x > 0 else 0 for x in values]
Examples
Pitfalls
x = 'yes' if cond
x = 'yes' if cond else None
[x if x > 2 else 0 for x in [1, 2, 3]]
[x for x in [1, 2, 3] if x > 2]
s = 'a' if n == 1 else 'b' if n == 2 else 'c' if n == 3 else 'd'
s = {1: 'a', 2: 'b', 3: 'c'}.get(n, 'd')
'a' + 'b' if False else 'c'
'a' + ('b' if False else 'c')
When to use
- 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
- 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
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'