Register Login

Ternary Operator in Python

Updated May 20, 2023

Different programming languages support ternary operators, and Python is one of them. Users can term the ternary operators as conditional expressions that help to insert conditions in a Python program.

Though, in Python, a conditional operation has the lowest preference of all Python operations. Still, there are several applications of ternary operators for programmers.

This article will discuss the ternary operator, how it works in Python, and some common examples of a ternary operator with explanations.

What is a ternary operator in programming?

In cases when users want to add decision-making statements, they can use this ternary operator. It is better to use this operator compared to using longer conditional statements like if and else in some cases.

Thus, using this conditional operator, users can simply test a condition in a single line that replaces the multiline if-else, which increases the code readability. In other terms, the ternary operator defines using the conditional operator on three operands or variables.

Syntax:

[val_true] if [condition] else [val_false]
expression : conditional_expr | lambda_expression

Parameters used in a Ternary Operator in Python

Users can specify three operands as the arguments, and these are:

  • Condition: This operand specifies a Boolean expression that the condition evaluates as either true or false.
  • val_true: If the above operand evaluates to be true, then the conditional operator assigns the value to this val_true operand.
  • val_false: If the above operand evaluates to be false, then the conditional operator assigns the value to this val_false operand.

Examples of using the ternary operator in Python:

Program using the if-else Statement

Code Snippet:

x, y = 1.346, 32.44
if x > y:
   Demo= x
else:
   Demo = y
print(demo)

Output:

Program using the if-else ternary operator

Code Snippet:

x, y = 1.346, 32.44
demo = x if x < y else y
print(demo)

Output:

Explanation:

In the above example, we used the expression demo to print x or y based on the given condition. For example, if x is less than y, then the output is x, and if x is not less than y, the conditional operator will print y as the output.

Example 2: Ternary operator as nested if-else

Code Snippet:

x, y = 23.443, 12.08442
print ("This implies x and y are equal" if x == y else "This implies x is greater than y"
		if x > y else "This implies y is greater than x")

Output:

Explanation:

In this example, we used the ternary operator as nested if-else, where we specified three operands with conditions. If x and y are equal, the operator will print the "This implies x and y are equal" statement in the first condition.

If x is greater than y, it will return "This implies x is greater than y," lastly, if y is greater than x, the ternary operator will return "This implies y is greater than x."

Time and space complexity:

Time Complexity is O(1), and Auxiliary Space is O(1).

Example 3: Using the print function with the ternary operator

Let us see how the print() function works inside the conditional operator:

x = 10
y = 20
print(x,"is greater than 20") if (x > y) else print(y,"is greater than 10")

Output:

Explanation:

Using the print() function, we have printed the greatest number of the two. The ternary operator will check and find the largest number among two integers.

Time and space complexity:

Time Complexity is O(1), and Auxiliary Space is O(1).

Example 4: Using the for loop with the ternary operator

Users can use the for statement to iterate over the elements they want to evaluate. Then the ternary operator will evaluate each element of the variable specified. Lastly, users can print the result of the ternary operator on the output console.

In this example, you will learn with steps how to use for loop with a ternary operator and use a condition.

Code Snippet:

demo = [9.0, 4.0, 2.1, 5, 8]
for i in demo:
    res = 'even' if i % 2 == 0 else 'odd'
    print(f'Given number {i} is {res}.')

Output:

Explanation:

Here, we created a Python list named "demo" and added the data inside the list. Then, we used the for statement to iterate over each element in the list.

Then applying the ternary operator, we specified whether each number is even or odd. We stored the result of the ternary operator in the variable called the "res." Lastly, we used the print() function to print the output of the ternary operator for each element of the Python list.

Time Complexity:

The above code snippet will hold a time complexity of O(n), where n is the number of elements the Python list has. It is since the code has iterables that iterate through each value in the list to evaluate whether the number is even or odd.

Space Complexity:

Since the above code only uses hardly one or two variables to hold the input and the results, it has a space complexity of O(1).

Example 5: Using ternary operator with tuple

We can also use the ternary operator with tuples, and the following syntax will show how to use it:

(<OnFalse>, <OnTrue>)[<condition>]

Parameters used:

<OnTrue> indicates when the condition is True, it will return the expression of this operator.
<OnFalse> means when the condition is False, it will return the expression of this operator.
<condition> defines the conditional expression that defines whether the operator will return the <OnTrue> or <OnFalse> expression.

Code Snippet:

a = 'Python'
b = 'JavaScript'
c = True
print(b if c else a) 
print((b, a)[c])
c = False
print(a if c else b) 
print((a, b)[c]) 

Output:

Explanation:

Here, we passed two string values, "Python" and "JavaScript," and then used the ternary operator with a tuple. According to the condition, the operator will return the string against the particular variable, whether a or b.

Example 6: Using ternary operator with dictionary

It is as easy to use the dictionary with the ternary operator. We can return the key of the dictionary if it exists, else the operator will return a fallback function, and the syntax is as follows:

a = dict["key"] if dict.has_key("key") else "fallback_function"

Code Snippet:

dict = {'a': 1, 'b': 2}
dict_key = 'a'
a = dict[dict_key] if dict_key in dict else -1
print(a)
dict_key = 'c'
a = dict[dict_key] if dict_key in dict else -1
print(a)

Output:

Explanation:

The operator returns the value of the specified key in the condition, and if it does not find the key, it returns -1.

Example 7: Using ternary operator with lambda function

Similar to the above two methods, we can use the ternary operator with the lambda function. The lambda function is an anonymous user-defined function in Python that can take numerous parameters.

Code Snippet:

def func1(a):
    if a > 50:
        a = 1*a
    else:
        a = 2*a
    return a
func2 = lambda a: 1*a if a>50 else 2*a
print(func1(10) == func2(10))

Output:

Explanation:

The lambda function works with the ternary operator and returns either True or False based on the condition we passed in the function.

Some significant discussions on the Ternary Operator

While dealing with ternary operators, users must understand these crucial points in brief before using them in the program:

  • In the first step, the operator will check and evaluate the given condition (x < y), then it will return either x or y depending on the Boolean value returned by the ternary operator condition.
  • The ternary operator is available in other programming languages, but the syntax or the order of the operands (arguments) in Python is distinct from other languages, such as C/C++.
  • Programmers rarely use a conditional expression like the ternary operator, which has the lowest preference among all Python operations.

Conclusion:

We hope this article has given a painstaking idea of the Python ternary operator. This article also highlighted all the related topics of the Python ternary operator with different examples that programmers can easily understand and use in their Python programs.


×