conditional expressions

Alex Martelli aleax at
Fri Sep 27 03:23:53 EDT 2002

Terry Reedy wrote:

> "Alex Martelli" <aleax at> wrote in message
> news:7nHk9.172208$pX1.6117207 at
>> The reason
>>         zz = a and b or c
>> is not the same thing as
>>         zz = a ? b : c
>> is that, when a is true and b is false, the former returns c,
>> while the latter returns b.
> In almost all the practical cases where I have thought about using
> this,  b is *not* false or cannot become false, in which important and
> real case the two expressions *are* equivalent.

A typical, frequent, practical case is classification, e.g.:

"Append bleep to list truebleeps when bleep is true, append it
to list falsebleeps instead when false".

If we had a ternary operator, a natural way of expression would be:


Of course this would be a disaster with the and/or idiom instead:

    (bleep and truebleeps or falsebleeps).append(bleep)

As list truebleeps starts out empty, thus false, this buggy code
would NEVER append anything to it.

In this case, like in most others (but far from all!) we don't
need short-circuiting, so we can perfectly well code:

    (truebleeps, falsebleeps)[not bleep].append(bleep)

This is now correct -- but still nowhere as clear as good old:

    if bleep: truebleeps.append(bleep)
    else: falsebleeps.append(bleep)

which to me remains the canonical way to code this in Python.
Yes, it IS fractionally more verbose, but, so what?  It's
immediately obvious, simple, and not clever.

> I think this is an elegant hack, and so I shared it in response to the
> OP.  Others think it ugly.  So be it.

It's _dangerous_ -- to use it, one always has to be fully aware
of the risk that subexpression b might be false.  I think this
is a pitfall just waiting for the unwary to stumble.  Not being
an aesthete, I consider that more important than issues of beauty.


More information about the Python-list mailing list