Python One Line Ternary

5/5 - (10 votes)

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.

The Python Ternary Operator -- And a Surprising One-Liner Hack

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.

Python Ternary Operator

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:

<OnTrue> if <Condition> else <OnFalse>
<OnTrue>The return expression of the operator in case the condition evaluates to True
<Condition>The condition that determines whether to return the <On True> or the <On False> branch.
<OnFalse>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!

👉 Recommended Tutorial: If Then Else in One Line Python

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<20 else 'What?')

# Method 2: Ternary Tuple
# (onFalse, onTrue) [condition]
print(('wtf', 'What?')[age<20])

# Method 3: Ternary Dictionary
# Use Dictionary True/False values
print({True: 'wtf', False: 'What?'}[age<20])

# Method 4: Ternary Lambda
# Lambda function with 0 arguments
# Execute only one branch expression --> more efficient
print((lambda: 'wtf', lambda:'What?')[age<20]())

Some of them are pretty confusing, right? Stay with me for a moment because you’ll learn about each of those next! 🙂

Basic Ternary

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.

This allows you to assign values to a variable conditionally using the ternary operator. You can also print values conditionally by passing a basic ternary operator into the print() function:

age = 17
print('wtf' if age<20 else 'What?')

The condition c=age<20 evaluates to True. Thus, the first part of the ternary operator x='wtf' is returned and passed into the print() statement. On the other hand, people older than 20 years would tend to ask 'What?' rather than 'wtf' so this would be the output of the ternary operator.

Python Ternary Tuple

Python Ternary Tuple Syntax

A shorthand form of the ternary operator is the following tuple syntax.

Syntax: You can use the tuple syntax (x, y)[c] consisting of a tuple (x, y) and a condition c enclosed in a square bracket. Here’s a more intuitive way to represent this tuple syntax.

(<OnFalse>, <OnTrue>)[<Condition>]
<OnTrue>The return expression of the operator in case the condition evaluates to True
<Condition>The condition that determines whether to return the <On True> or the <On False> branch.
<OnFalse>The return expression of the operator in case the condition evaluates to False
Tuple Syntax of the Ternary Operator

In fact, the order of the <OnFalse> and <OnTrue> operands is just flipped when compared to the basic ternary operator. First, you have the branch that’s returned if the condition does NOT hold. Second, you run the branch that’s returned if the condition holds.

age = 17
print(('wtf', 'What?')[age<20])

The condition age<20 holds so the return value passed into the print() function is the <OnTrue> branch 'What?'. Don’t worry if this confuses you—you’re not alone. Let’s clarify why this tuple syntax works the way it does!

First, you create a tuple ('wtf', 'What?'). To access the first tuple value 'wtf', you’d use the standard indexing syntax ('wtf', 'What?')[0]. To access the second tuple value 'What?', you’d use the standard indexing syntax ('wtf', 'What?')[1].

Second, you create a condition age<20. You use this condition as the indexing value. You end up with either ('wtf', 'What?')[False] or ('wtf', 'What?')[True]. As you may know, the Booleans False and True are represented through integers 0 and 1 in Python. Thus, you get ('wtf', 'What?')[0] and ('wtf', 'What?')[1], respectively.

In other words: if your condition evaluates to False, you access the first tuple value. If your condition evaluates to True, you access the second tuple value.

Python Ternary Dictionary

Problem: Given a dictionary and a key. Can you use the ternary operator to return the key from the dictionary, but only if it exists to avoid the key error? If the key doesn’t exist, a “fall-back” function should be executed.

Example: Say, you want to do something like the following (pseudocode):

var = dict["key"] if dict.has_key("key") else "fallback"

Solution: You can use the ternary operator dict[key] if key in dict else "fallback" to accomplish this:

d = {'Alice': 17, 'Bob': 22}
key = 'Alice'

# Has key:
var = d[key] if key in d else -1
# 17

# Doesn't have key:
key = 'Ann'
var = d[key] if key in d else -1
# -1

The ternary operator returns the value associated to the given key—but only if the key exists. If it doesn’t exist, it returns the default value -1.

However, a more Pythonic way to accomplish the same thing in a more readable and more concise way is to use the dictionary.get(key, default) function:

d = {'Alice': 17, 'Bob': 22}
key = 'Alice'

# Has key:
var = d.get(key, -1)
# 17

# Doesn't have key:
key = 'Ann'
var = d.get(key, -1)
# -1

The outer structure of the code is the same—but the get function with default value -1 semantically replaces the more complicated ternary operator.

Python Ternary Lambda

You can also write conditional statements in a lambda function. Oftentimes, this results in a more concise and more readable way of accomplishing the same thing. Say, you’ve got the following example:

def f(x):
    if x > 100:
        x = 1.1*x
        x = 1.05*x
    return x

# 105.0

The function f(x) takes one argument x and increases it by 10% if the argument is larger than 100. Otherwise, it increases it by 5%. As it turns out, you can also use the ternary operator effectively:

f = lambda x: 1.1*x if x>100 else 1.05*x

# 105.0

The result is the same. An intermediate to advanced Python coder will have no problem understanding the code and it’s much more concise. That’s why I’d prefer this way over the first one.

Python Ternary Multiple Lines

What if you have a ternary operator that’s very long?

var = 'I want to learn Python' if 42**2<166 else 'I want to learn Go programming'
# I want to learn Go programming

Problem: How to write the ternary operator in multiple lines?

Solution: You can extend any logical line in Python over multiple physical lines by using the parenthesis.

var = 'I want to learn Python' if 42**2<166 else 'I want to learn Go programming'

var = ('I want to learn Python'
       if 42**2<166 else
       'I want to learn Go programming')
# I want to learn Go programming

This is the PEP8 standard way of breaking long lines—if you cannot do it in a more natural way (such as avoiding the ternary operator and using the if statement in this example).

Python Ternary Elif

Python Ternary Elif

By now, you’ve learned how to write the if-else statement in a single line of code using the ternary operator. But can you do the same with an elif statement if you have multiple conditions?

Of course, you can! (If you’re in doubt about whether you can do XYZ in a single line of Python, just assume that you can. Check out my new book “Python One-Liners” to master the single line of code!)

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

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

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
    y = 4
# 2

# Method 2: Nested Ternary Operator
y = 1 if x > 42 else 2 if x == 42 else 3 if x == 12 else 4
# 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:

List Comprehension
A Simple Introduction to List Comprehension in Python

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
# 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<20 else print('hello')
# hello

Of course, this is not very clean and readable Python code—a better alternative would be to use a simple if statement:

# Better alternative:
if age<20:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

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

Python One-Liners - Trick 3 Lambda, Map, and Ternary Operator