Signup/Sign In

Ternary Conditional Operator in Python 

Posted in Programming   LAST UPDATED: JUNE 3, 2022

    Ternary operators, also known as conditional expressions, evaluate the data supplied to them and return True or False based on the fulfillment of the condition. In Python, the ternary operator returns a value based on the result of a binary condition. It looks like a "if-else" condition block since it takes a binary value(condition) as an input. It does, however, return a value, making it similar to a function.

    Syntax of Ternary Operator in Python

    [when_true] if [expression] else [when_false]

    Note: Always remember that the [when_true] expression shouldn't be false or 0. If the [when_true] is false, the [when_false] gets executed irrespective of the conditions provided to it. This happens because, when the [expression] is true, the python interpreter goes on to execute [when_true]. Upon seeing that it is 0 or False, the python interpreter goes on to execute the [when_false] condition.

    a). Using python if-else statement -

    >>> a, b = 2, 3
    >>> if a>b:
       print("a")
    else:
       print("b")
    b

    b). Using Python ternary operator

    >>> a, b = 2, 3
    >>> print("a" if a> b else "b")
    b

    Example of Ternary Operator in Python

    Let's take a super simple example to see how the ternary operator works,

    m , n = 12, 56
    
    min_val = m if m < n else n   # get the smallest value among the 2 values
    print(min_val) 

    Output:

    12

    The above ternary operator's if...else equivalent would be,

    m , n = 12, 56
    
    if m>n:
        min_val = n
    else:
        min_val = m
        
    print(min_val) 

    Output:

    12

    It can clearly be seen that the number of lines to code the same has been reduced to a great extent. Now let's see a few more code examples.

    1. Python tuples with ternary operators

    The tuple data structure can be used to specify the operation which needs to be performed when the condition is True or False.

    Let's see a simple example,

    m , n = 12, 56
    (n,m) [m<n]

    Output:

    12

    2. Python dictionaries with ternary operators

    Similar to tuples, a dictionary data structure can be used to specify the output of evaluating the expression. In the below example, the first argument corresponds to a False value and the second argument corresponds to a True value, and the evaluating condition is present in the square brackets [m<n].

    m , n = 12, 56
    {False:f"n:{n}",True:f"m:{m}"}[m<n]

    Output:

    'm:12'

    3. Lambda with ternary operators

    The lambda function can be used to behave like a ternary operator. More about Lambda functions can be found here.

    Let's see a simple example,

    m , n = 12, 56
    (lambda :f"n:{n}",lambda :f"m:{m}")[m<n]()

    Output:

    'm:12'

    4. Nested ternary operators

    The ternary operators can be chained to evaluate to a certain value (True/False) based on a given expression.

    Let's see a simple example,

    m = 12
    "Less than 56" if m<56 else "Between 12 and 56" if m>=12 and m<=56 else "Greater than 12"

    Output:

    'Less than 56'

    Note

    • First, the specified condition is evaluated (a < b), and then, depending on the Boolean value returned by the condition, either an or b is returned.
    • In other languages, such as C/C++, the order of the parameters in the operator is different.
    • Among all Python operations, conditional expressions have the lowest priority.

    Conclusion:

    In this post, we understood what ternary operators are, their significance and how they make the code compact. We also saw how ternary operators can be used with different data structures. Don't forget to share your take on ternary operators in the comment section below.

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:PythonPython Operators
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS