Python: ternary operator

In C language (and many other languages), there is a compact ternary conditional operator that is a compact if-else conditional construct. For instance, in C, a traditional if-else construct looks like:

and the equivalent ternary operator looks like:

As in the if-else code, only one expression x or y is evaluated.

In Python, from version 2.5, you would write:

More formally the ternary operator is written as:

So condition is evaluated first then either x or y is returned based on the boolean value of condition.

You can use ternary operator within list comprehension. For example:

This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published.