Python ternary operator with Examples

Python ternary operator is also termed as conditional operator. This is because it can evaluate a statement with a condition being true or false.

Python ternary operator

  • Python ternary operator was introduced in Python 2.5.
  • If used properly, ternary operator can reduce code size and increase readability of the code.
  • There is no special keyword for ternary operator, it’s the way of writing if-else statement that creates a ternary statement or conditional expression.

Python ternary operator syntax

Python ternary operator is written with simple syntax using if else statement.

Python ternary operator example

On the above syntax, let us quickly build up an example:

Clearly, the presented example is a lot more readable than the usual if statement, as follows:

Of course, python ternary operator made above code very small.

A very easy way to remember the order of condition is just like you think it, for example, based on above code snippet, we say “Car is Ferrari if it is fast otherwise it is Sedan”, sounds easy now, right?

Python ternary operator example with Tuple

The operation shown in the earlier section was a simple replacement for if-else conditions. Well, Ternary operators are much more powerful than those.

We can use ternary operator with tuple too.

Please note that in this syntax, False value is before True value. Consider this more complex example which works with Tuples:

This is a very less used syntax as it might not represent clear readability like before. Also, it’s important to consider the performance of this method as this will result in both elements of the Tuple being evaluated. The earlier ternary operator didn’t result in this lag. Below image shows the output of ternary operator example code.

python-ternary-operator

Python ternary operator advantages

Main advantages offered by ternary operator are:

  • It allows us to replace simple if statements with a single line expression.
  • Increases code readability by reducing number of lines of code.

In this quick lesson, we studied the ternary operators in Python which were introduced in Python 2.5. Use them to shorten your code and make it more maintainable and easily readable.

By admin

Leave a Reply

%d bloggers like this: