Python Ternary Elif

Summary: To use an elif branch in the ternary operator, use another ternary operator as the result of the else branch (nested ternary operator). The nested ternary operator x if c0 else y if c1 else z returns x if condition c0 is met, else if (elif) condition c1 is met, it returns y, else it returns z.

Python Ternary Elif

Problem: You may have seen the ternary operator x if c else y. Is there a similar ternary operator with an additional elif statement? In pseudocode, you want something like:

# Pseudocode
x if c elif y0 else y1

In other words: What’s the best way of extending the ternary operator to what you may call a “quaternary” operator?

Background: 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.

Learn more about the ternary operator in our detailed blog article!

Example: Say, you want to write the following if-then-else condition in a single line of code:

>>> x = 42
>>> 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):

Method: Nested Ternary Operator

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 ;))!

Python Ternary Multiple Elif

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!

Discussion

However, even if the nested ternary operator is more concise than an if-elif-else statement, it’s not recommended because of readability of your code. Most programmers don’t have any trouble understanding a simple if-elif-else statement. But a nested ternary operator is an advanced-level piece of Python code and especially beginners will struggle understanding it.

So, it’s great that you’ve expanded your One-Liner Superpower. But you should use it wisely!

Related Video: If-Then-Else in One Line of Python Code

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!