Ternary operator python list comprehension

The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

Ternary [from Latin ternarius] is an adjective meaning “composed of three items”. [source] So, literally, the ternary operator in Python is composed of three operands. In many Python circles, the ternary operator is also called “conditional expression” because it executes a given expression only if a condition is met.

Syntax: The three operands are written as x if c else y which reads as “return x if c else return y“. Let’s write this more intuitively as:

if else OperandDescription
The return expression of the operator in case the condition evaluates to True
The condition that determines whether to return the or the branch.
The return expression of the operator in case the condition evaluates to False
Operands of the Ternary Operator

Let’s have a look at a minimal example in our interactive code shell:

Exercise: Run the code and input your age. What’s the output? Run the code again and try to change the output!

Let’s dive into the different variants of the Ternary operator in Python!

Python Ternary Examples

Let’s have a quick overview of a few examples on different methods to use the ternary operator:

age = 17 # Method 1: Basic Ternary print['wtf' if age> if x > 42: >>> print["no"] >>> elif x == 42: >>> print["yes"] >>> else: >>> print["maybe"] yes

The elif branch wins: you print the output "yes" to the shell. But how to do it in a single line of code? Just use the ternary operator with an elif statement won’t work [it’ll throw a syntax error].

The answer is simple: nest two ternary operators like so:

>>> print["no"] if x > 42 else print["yes"] if x == 42 else print["maybe"] yes

If the value x is larger than 42, we print “no” to the shell. Otherwise, we execute the remainder of the code [which is a ternary operator by itself]. If the value x is equal to 42, we print “yes”, otherwise “maybe”.

So by nesting multiple ternary operators, we can greatly increase our Python one-liner power!

Try it yourself:

Exercise: Which method is more concise? Count the number of characters [or write a small script that does it for you ;]]!

Related Article: Python Ternary Elif

Python Ternary Nested

In the previous example, you’ve seen how a nested ternary operator semantically adds an elif branch. In theory, you can add an arbitrary number of elif branches by nesting more and more ternary operators:

# Method 1: If ... Elif ... Else x = 42 if x > 42: y = 1 elif x == 42: y = 2 elif x == 12: y = 3 else: y = 4 print[y] # 2 # Method 2: Nested Ternary Operator y = 1 if x > 42 else 2 if x == 42 else 3 if x == 12 else 4 print[y] # 2

However, readability suffers badly and you shouldn’t do anything of the sort. A simple mult-line if ... elif ... elif ... else statement is better!

Python Ternary Evaluation Order

Problem: Given a ternary operator X if C else Y that returns expression X if condition C is met, and returns expression Y otherwise. What’s the evaluation order of these expressions? Will expression X evaluate even if condition C is False?

Solution: According to the official Python documentation: “The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.”

So, only the matching condition is evaluated as can be seen in the following code example:

print['X'] if 5>3 else print['Y'] # X

You run the expression print['X'] if the condition 5>3 evaluates to True [which it does]. The interesting observation is that the expression print['Y'] is not executed!

Python Ternary in List Comprehension

You can use the ternary operator as the expression part of a list comprehension statement. Let’s recap list comprehensions quickly:

Instead of using a unary expression, you can use a ternary expression:

print[[x**2 if x%2 else x for x in range[5]]] # [0, 1, 2, 9, 4]

You use the ternary operation x**2 if x%2 else x to return the square number only for odd values. Even values remain unchanged.

Python Ternary Pep8 Pythonic

Is the Python ternary operator good style or bad?

The ternary operator is good and Pythonic style that satisfies the PEP8 standard. Some unspoken rules are:

  • The if branch should be the most likely one.
  • Don’t use nested ternary operators [use plain multi-line if ... elif ... then ... statements instead].
  • Don’t use long ternary operators with complicated expressions [again use multi-line if statements instead].

Python Ternary Can’t Assign to Conditional Expression

If you use the ternary operator in the wrong way, it’ll throw a SyntaxError:

You can resolve the SyntaxError: can’t assign to conditional expression by avoiding to use an assignment statement inside your ternary operator. Instead, assign the return value of the ternary operator to a variable if you must:

a = 2 if 5>2 else 4 print[a] # 2

Now, the code doesn’t throw another error.

Python Ternary None

You can use any return value in the ternary operator—even None. For example, you’ll often see ternary operators that actually return nothing and that just execute a certain function without return value:

age = 20 # Ternary operator returns None print['hi'] if age

Chủ Đề