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:

if (a > b) {
    result = x;
} else {
    result = y;
}

and the equivalent ternary operator looks like:

result = a>b ? x : y;

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

In Python, from version 2.5, you would write:

results = x if a > b else y

More formally the ternary operator is written as:

x if condition else y

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:

[1 if item > else -1 for item in [0,1,-5,2]]
Please follow and like us:
This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published.