Re: Looking for ?: operator...

Guido.van.Rossum@cwi.nl
Fri, 16 Sep 1994 12:31:14 +0200

> Is there something I can use similar to C's ?: operator?? I have tried
> to think of a way to coax lambda into doing it, but cant think of a
> method.

Jack pointed out that in many cases you can mimic a?b:c with "a and b
or c", but there's a flaw: if b is zero (or empty, or None -- anything
that tests false) then c will be selected instead. In many cases you
can prove by looking at the code that this can't happen (e.g. because
b is a constant or has a type that can never be false), but in general
this can be a problem.

Steve Majewski (or was it Tim Peters?) suggested the following
solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
is never false, so the wrong path is never taken; then applying [0] to
the whole thing gets the b or c that you really wanted. Ugly, but it
gets you there in the rare cases where it is really inconvenient to
rewrite your code using 'if'.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>