the PHP ternary operator equivalent on Python

Steven D'Aprano steve at
Sat Nov 19 05:22:11 CET 2005

On Fri, 18 Nov 2005 11:17:17 -0800, David  Wahler wrote:

> Daniel Crespo wrote:
>> I would like to know how can I do the PHP ternary operator/statement
>> (... ? ... : ...) in Python...
>> I want to something like:
>> a = {'Huge': (quantity>90) ? True : False}
> Well, in your example the '>' operator already returns a boolean value
> so you can just use it directly. Hoewver, I agree that there are
> situations in which a ternary operator would be nice. Unfortunately,
> Python doesn't support this directly; the closest approximation I've
> found is:
>>>> (value_if_false, value_if_true)[boolean_value]

Which doesn't short-circuit: both value_if_false and value_if_true are

WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
    x = true_value
    x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a


More information about the Python-list mailing list