Python Ternary Operator with Best Example Programs

Python is famous for being a flexible language that is suitable for machine learning and data analytics (Pandas).

For this reason, programmers are struggling with how to gain more skills that would boost their careers in Python.

What is a Python ternary operator?

Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. They became a part of Python in version 2.4.

Ternary operators are single-line replacements of multi-line if-else statements.

It makes your code look cleaner and more compact.

Additional information from Python Documentation, the expression x if C else y first evaluates the condition, d rather than x.

If Cs is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

Syntax:

var = [true_val] if [condition] else [false_val]

  • true_val: If the expression evaluates to true, this value will be assigned.
  • condition: A boolean expression that returns true or false.
  • false_val: If the expression evaluates to false, this value will be assigned.

On the left side of the assignment operator (=), the variable var will be given true_val if the boolean expression evaluates to true and false_val if it evaluates to false

Simple Method to Use Ternary Operator Example Program

The first task that you’re about to see is an example program using the simple method of the ternary operator.

This program will demonstrate Python ternary in a simple conditional operator.

x, y = 5, 29

a = x if x < y else y
 
print(a)

In this example, the inputs are variables x and y with the values 5 and 29. Therefore the x, y = 5, 29 line of code expresses that x is equal to 5 and y is equal to 29.

Now to implement the Python ternary operator, the a = x if x < y else y is applied.

Based on the syntax given, a represents the var, the x and y represents the true_val/false_val, and < is the condition.

Output: 

5

The output then shows “5” since 5 (value of x) is less than 29 (value of y) upon program execution.

Direct Method by using tuples, Dictionary, and lambda example program

Now, let’s get into the direct method of the ternary operator through Python tuples, dictionary, and lambda program examples.

The condition > is used in the following examples where the outputs from the examples depend on.

Example 1: Tuples

x, y = 5, 29

a = (y, x) [x > y]

print(a)

Output:

29

Example 2: Dictionary

x, y = 5, 29

a = {True: x, False: y} [x > y]

print(a)

Output:

29

Example 3: Using lambda

x, y = 5, 29

a = (lambda: y, lambda: x)[x > y]()

print(a)

Output:

29

Examples 1, 2, and 3 demonstrate how the ternary operator works with a tuple, dictionary, and lambda in Python.

The operator selects one output from the given items according to the condition provided.

Time Complexity: O(1)

Auxiliary Space: O(1)

Ternary operator can be written as Nested if-else Example Program

The demonstration below is an example of how we use the ternary operator with the nested if-else statement.

Example: Nested If-else Statement

x, y = 5, 29

print("X and Y are equal" if x == y else "X is greater than Y"
        if x > y else "Y is greater than X")

Output:

Y is greater than X

The implementation of the ternary operator with nested if-else is clarified in the example.

However, the above line of codes can also be available as:

Example:

x, y = 5, 29

if x != y:
    if x < y:
        print("X is less than Y")
    else:
        print("Y is less than X")
else:
    print("X and Y are equal")

Output:

X is less than Y

The algorithms in the examples above were still the same.

The only difference is the arrangement of codes and the conditions we used.

Nevertheless, the output in the second example was still in synonym with the output from the first example.

To use the print function in the ternary operator example program

For the next example, we will use the Python ternary operator to find the larger number from the given inputs.

Example:

x, y = 5, 29

print(x,"is greater") if (x > y) else print(y,"is greater")

Output:

29 is greater

In this example, we directly apply the operator within the print() function.

The ternary operator of Python is placed within the print() function along with the true_val/false_val (x, y) and the condition > (x > y).

What is an alternative of ternary operator in Python?

Aside from the ternary operator, you may also use tuple as a simple alternative for the if-else ternary operator.

Syntax:

(true_value, false_value)[conditional_expression]

False_value and true_value are the two elements that make up the tuple.

In addition, the conditional expression replaces an index within the square bracket notation.

This works because True has a value of 1 and False has a value of 0.

Summary

In summary, the main function of the Python ternary operator is to simplify the complex codes of if-else statements.

This operator is useful for making the program more readable and understandable.

As a result, the operator is flexible and applicable in multiple forms of Python objects and arguments.

This is also useful for true or false outputs and/or arguments with inputs of not more than two.

You can also check out the Python Import from Parent Directory in Simple Way.

If you want more discussions from us, comment down.

Leave a Comment