Ternary conditional operator is a type of conditional operator which returns a value on basis of a condition.  The ternary operator is used for d

Does Python have a Ternary Conditional Operator?

submited by
Style Pass
2021-05-13 11:19:09

Ternary conditional operator is a type of conditional operator which returns a value on basis of a condition.  The ternary operator is used for decision making in place of whole If-else conditional statements. A ternary operator does this job in just one statement.

The above example is not widely used and is generally disliked by Pythonistas for not being Pythonic. It is also easy to confuse where to put the true value and where to put the false value in the tuple. Another reason to avoid using a tupled ternery is that it results in both elements of the tuple being evaluated, whereas the if-else ternary operator does not.

This happens because in the case of tuple ternary operator first the tuple is built then the index is found so both cases are executed in this case. But in the If-else ternary it follows the logic of If-Else statement so either the true or false case is executed. So, using if-else ternary is better and recommended than using tuple ternary operator.

In python there is also the shorthand ternary tag which is a shorter version of the normal ternary operator you have seen above.

Leave a Comment