The most basic ternary operator
x if c else y returns expression
x if the Boolean expression
c evaluates to
True. Otherwise, if the expression
c evaluates to
False, the ternary operator returns the alternative expression
Here’s a minimal example:
var = 21 if 3<2 else 42 # var == 42
While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:
Introduction and Overview
Python is so powerful, you can even compress whole algorithms in a single line of code. So the natural question arises: can you write conditional if-then-else statements in a single line of code? This article explores this mission-critical question in all detail.
Is it possible to write the if-then-else statement in a single line of code?
Yes, you can write most if statements in a single line of Python using any of the following methods:
- Write the if statement without else branch as a Python one-liner:
if 42 in range(100): print("42").
- If you want to set a variable, use the ternary operator:
x = "Alice" if "Jon" in "My name is Jonas" else "Bob".
- If you want to conditionally execute a function, still use the ternary operator:
print("42") if 42 in range(100) else print("21").
In the previous paragraph, you’ve unwillingly learned about the ternary operator in Python. The ternary operator is something you’ll see in most advanced code bases so make sure to understand it thoroughly by reading the following section of this article.
Before you and I move on, let me present our brand-new Python book Python One-Liners.
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Let’s dive into the three different ways to write the if-then-else statement as a Python one-liner.
Related articles: Python One Line Ternary
How to Write the If-Then-Else Statement as a Python One-Liner?
Let’s have a look at all the ways how you can write the if-then-else statement in one line. The trivial answer is to just write it in one line—but only if you don’t have an else branch:
Case 1: You Don’t Have an Else Branch
Consider the following code snippet where you check for the number 42 whether it falls in a range of numbers:
>>> if 42 in range(100): >>> print("42") 42
This code snippet will indeed print the output because the integer 42 falls into the range of numbers from 0 to 99. But how can we write this if statement in a single line of code? Just use a single line like this:
>>> if 42 in range(100): print("42") 42
The two statements are identical so this is the way to do it—if you can write the conditional body in a single line of code.
However, if you try to become too fancy, it won’t work:
>>> if 42 in range(100): print("42") else print("21") # "Error: invalid syntax"
Python cannot handle this anymore: the interpreter throws an “invalid syntax” error.
But don’t worry, there’s a workaround: the ternary operator.
Case 2: You Have an Else Branch And You Want to Conditionally Assign a Value
In case you have an else branch and you want to conditionally assign a value to a variable, the ternary operator is your friend. Say, you want to write the following if-then-else statement in a single line of code:
>>> if "Jon" in "My name is Jonas": >>> x = "Alice" >>> else: >>> x = "Bob" >>> print(x) Alice
As the string
"Jon" appears in the string
"My name is Jonas", the variable
x will take value
"Alice". Can we write it in a single line? Sure—by using the so-called ternary operator.
x = "Alice" if "Jon" in "My name is Jonas" else "Bob"
The ternary operator is very intuitive. Just read if from left to right and you’ll understand its meaning. We assign the value
"Alice" to the variable
x in case the following condition holds:
"My name is Jonas". Otherwise, we assign the string
"Bob" to the variable
Ternary Operator Syntax: The three operands are written as
x if c else y which reads as “return
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 |
|<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 |
Case 3: What If We Don’t Want to Assign Any Value But We Have an Else Branch?
Well, there’s a quick and dirty hack: just ignore the return value of the ternary operator. Say, we want to compress the following if-then-else statement in a single line of code:
if 42 in range(100): print("42") else: print("21")
The problem is that we don’t have a return value. So can we still use the ternary operator? As it turns out, we can. Let’s write this if-then-else statement in a single line:
>>> print("42") if 42 in range(100) else print("21") 42
We use the ternary operator. The return value of the
print() function is simply None. But we don’t really care about the return value, so we don’t store it in any variable. We only care about executing the print function in case the if condition is met.
How to Write an If-Elif-Else Statement in a Single Line of Python?
In the previous paragraphs, you’ve learned that we can write the if-else statement in a single line of code. But can we do the same with an elif statement if we 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.)
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: we 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!
Let’s quickly handle a bunch of related questions:
Python One Liner: How to Write If Without Else?
We’ve already seen an example above: we simply write the if statement in one line without using the ternary operator:
if 42 in range(100): print("42"). Python is perfectly able to understand a simple if statement without an else branch in a single line of code.
Python One Liner: How to Write Elif?
We cannot directly write the elif branch in one line of Python code. But we can nest two ternary operators instead:
>>> 100 if x > 42 else 42 if x == 42 else 0 42
Python If-Else One-Liner: What Does It Return?
The ternary operator always returns the result of the conditional evaluation. Again, the code snippet
100 if x>42 else 42 returns the integer value 42.
If you only execute functions within the ternary operator, it’ll return the
Related Video Tutorial
Master the power of the single line of code—get your Python One-Liners book now! (Amazon Link)
Where to Go From Here
Knowing small Python one-liner tricks such as the ternary operator is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.
If you want to learn the language Python by heart, join my free Python email course. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime. Try it!