Ternary Operator in Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

The ternary operator in Python is a concise way of writing simple if/else statements in a single line. It returns a true or false value by evaluating a boolean condition. It is shorter and more readable than simple if/else statements. We can also implement ternary operators with tuples, lists, dictionaries, or lambda functions. Ternary operators can also be nested by chaining them.

What is Ternary Operator in Python?

The ternary operator (also known as a conditional expression) is a concise way of writing conditional statements in Python. It returns a value based on the result of a boolean condition.

Sometimes writing traditional if/else statements can become hectic. For instance, using if/else to simply print something:

It took 4 lines for such a simple task, we can achieve the same result with ternary operators in a single line.

In the following sections, we will see how to use the ternary operator in Python.

Takeaway

  • The ternary operator is a way of writing simple if/else statements in a single line.

Syntax of Ternary Operator

Syntax:

The following image shows that the ternary operator returns value 1 when the condition is evaluated as true otherwise value 2 is returned: syntax of python ternary operator

Let's use the ternary operator to simplify the if/else statements written before.

Done! In just one line.

This conditional operator is given the name "ternary" because it is composed of three parts. Let's see each one of them in detail.

Takeaway

  • The ternary operator is composed of three operands.

Three Operands of Python Ternary Operator

The ternary operator includes three operands:

three operands of python ternary operator

  1. Condition: A boolean expression that evaluates to either True or False.
  2. True value: A value (any Python object) to return if the condition is evaluated to True.
  3. False value: A value (any Python object) to return if the condition is evaluated to False.

Takeaway

  • The ternary operator includes a condition to evaluate, a true value, and a false value to return based on that condition.

Example of Ternary Operator in Python

We have already seen how the ternary operator can be used to print different values. Let's see a couple more examples.

Example 1: Assigning Variable Using the Ternary Operator

The ternary operator allows us to assign one value to the variable if the condition is true, and another value if the condition is false.

Suppose we want to assign a variable action according to the value of the variable signal:

Set action to "move" if the value of the signal is "green light" otherwise set the action to "stop". assigning variable using the ternary operator

We can do this in a single line using the ternary operator:

Output:

Explanation:

First, the condition signal == "green light" is evaluated. As the value of the signal is "green light", the condition is evaluated to True and the first value of the ternary operator "move" is returned and then assigned to the variable action.

Example 2: Returning Values Using the Ternary Operator

Let's write a function that returns different fee amounts by checking if a customer is a member or not:

Output:

Explanation:

As the condition is_member is False this time, the second value is returned.

Takeaways

  • We can assign different values to a variable with the ternary operator depending on a condition.
  • We can use the ternary operator to return a value from a function depending on a condition.

Various Ways to Implement Ternary Operator in Python

Although we have the simple method of defining ternary operators as described above, we can also implement ternary operators using:

  • Tuple
  • List
  • Dictionary
  • Lambda Functions

1. Implementing Ternary Operator with Tuples

We can implement the ternary operator with tuples:

Tuples are immutable data structures defined with parenthesis that stores an ordered sequence of values. For example: (1, 2, 3) is a tuple with three values. As tuples are immutable, you can not change the values inside it after it is defined.

Syntax:

Example:

Output:

Explanation:

We first created a tuple - ("stop", "move") with values for both true and false conditions. Then we used indexing -[signal == "green light"] to select one of the values.

The reason this works is that the condition will return either False or True which will be converted to 0 or 1 respectively when indexing.

Thus, the first value (0th index) corresponds to False and the second value(1st index) corresponds to True.

As in our case, the condition evaluates to True, thus "move" is returned.

2. Implementing Ternary Operator with Lists

We can implement the ternary operator with lists:

  • Lists are mutable data structure defined with square brackets that stores an ordered sequence of values.
  • For example: [1, 2, 3] is a list with three values.
  • Lists are similar to tuples, but they are mutable which means we can change the values inside of it.

Syntax:

Example:

Output:

Explanation:

This example is similar to tuple one. We just used a list instead of a tuple, the working remains the same.

3. Implementing Ternary Operator with Dictionaries

We can implement the ternary operator with dictionaries:

A dictionary is a collection of key: value pairs where each value is accessed using a unique key. It is defined using curly braces. For example: {"name": "harry", "age": 11} is a dictionary with two keys. Values are accessed using keys instead of indexes as in lists.

Syntax:

Example:

Output:

Explanation:

In this case, also a dictionary is created first and then the condition is evaluated and matched against the keys of the dictionary which are either True or False, and the corresponding value is returned.

Unlike tuples or lists, the order of true or false values doesn't matter with the dictionary.

4. Implementing Ternary Operator with Lambda Functions

We can implement the ternary operator with lambda functions:

A lambda function is an anonymous function that is defined without a name using the lambda keyword instead of the usual def keyword. For example: double = lambda x: x * 2 is a lambda function that takes one argument x.

Syntax:

Example:

Output:

Explanation:

We can also provide a lambda function inside of the tuple instead of hard-coded values as done before. One of the lambda functions will be called based on the condition.

Takeaway

  • You can also implement ternary operators with a tuple, list, dictionary, or lambda functions.

Ternary Operator vs if/else

If we have done the same example using traditional if/else statements it would take 4 lines:

Set action to "move" if the value of the signal is "green light" otherwise set the action to "stop".

Output:

Now you can see for simple conditional statements, the ternary operator is a shorter and more readable choice than traditional if/else statements. ternary operator vs if else

Takeaway

  • Ternary operator is a better choice for simple if/else statements.

Nested Ternary Operator in Python

We can also nest ternary operators, here is an example:

Code:

Output:

This is equivalent to the following if/else statements:

Remember with great powers come great responsibility, just because you can nest ternary operators doesn't mean you should always do it. Nesting ternary operators may hurt readability and cause issues in development down the line.

Takeaway:

  • We can nest ternary operators by chaining them.
  • We should avoid nesting as it may hurt readability.

Also, check out this article to learn about Operators in Python.

Conclusion

  • The ternary operator is a concise way of writing simple if/else statements in a single line.
  • Syntax: true_value if condition else false_value.
  • Ternary operators include:
    • Condition
    • True value
    • False value
  • You can assign variables with ternary operators.
  • Ternary operators are shorter and more readable than simple if/else statements.
  • We can also implement ternary operators with:
    • Tuples
    • List
    • Dictionary
    • Lambda Functions
  • We can nest ternary operators by chaining them to write complex if/else statements. This hurts readability and should be avoided.