How to use ternary conditional operator in Python?

Posted by Editorial Staff | Updated on

After a long discussion I’ve decided to add a shortcut conditional
expression to Python 2.5.

The syntax will be

This first evaluates C; if it is true, A is evaluated to give the
result, otherwise, B is evaluated to give the result.

The priorities will be such that you can write

But you’d have to write

Note that all these are intentionally ugly. 🙂

In general, ‘if’ and ‘else’ bind less tight than everything except lambda.

We will adjust the syntax of what goes inside an ‘if’ to disallow
lambda; currently

is accepted but quite useless (it’s always true) so this will be disallowed.

Flames, pleas to reconsider, etc., to /dev/null.

Congratulations gracefully accepted.


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@] Your question and answer will appear on and help other developers.

Related Questions & Answers