Free Courses
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Ternary Operator in Python

Learn About Ternary Operator in Python.

Updated - 2 Jul 20228 mins readPublished : 26 Nov 2021
Published : 26 Nov 2021
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

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.

Scope

  • In this article, we will learn about ternary operators in Python and various ways and methods to use them, along with suitable examples.

What is Ternary Operator in Python?

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

if number % 2 == 0:
  print("Even")
else:
  print("Odd")

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

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.

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 Python Ternary Operator

Syntax:

true_value if condition else false_value

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.

print("Even" if number % 2 == 0 else "Odd")

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:

signal = "green light"
action = "move" if signal == "green light" else "stop"
print(action)

Output:

move

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:

def get_fee(is_member):
  return 10 if is_member else 20

print(get_fee(False))

Output:

20

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.

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".

signal = "green light"

if signal == "green light":
  action = "move"
else:
  action = "stop"

print(action)  

Output:

move

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.webpr

Takeaway

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

Other 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:

(false_value, true_value)[condition]

Example:

signal = "green light"
action = ("stop", "move")[signal == "green light"]
print(action)

Output:

move

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:

[false_value, true_value][conditon]

Example:

signal = "green light"
action = ["stop", "move"][signal == "green light"]
print(action)

Output:

move

Explanation:

This example is similar to tuple one. We just used a list instead of a tuple, the working remain 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:

{True: true_value, False: false_value}[condition]

Example:

signal = "green light"
action = {True: "move", False: "stop"}[signal == "green light"]
print(action)

Output:

move

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:

(lambda x: false_val, lambda x: true_val)[condition](args)

Example:

signal = "green light"
action = (lambda msg: f"stop {msg}", lambda msg: f"move {msg}")[signal == "green light"]("now")
print(action)

Output:

move now

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.

Nested Python Ternary Operator

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

Code:

signal = "red light"
action = "move" if signal == "green light" else "stop" if signal == "red light" else "Invalid Signal"
print(action)

Output:

stop

This is equivalent to the following if/else statements:

signal = "red light"

if signal == "green light":
  action = "move"
elif signal == "red light":
  action = "stop"
else:
  action = "Invalid Signal"


print(action)

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.

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 includes a:
    • 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.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors