07-19-2020, 03:38 AM
Python One Line If Without Else
Crafting beautiful Python one-liners is as much an art as it is a science. In this tutorial, you’ll learn how to compress an if statement without an else branch into a single line of Python code.
Problem: What’s the one-liner equivalent of the simple if statement without an else branch?
Here’s an example:
You may want to (i) print something, (ii) assign a value to a variable, or (iii) append an element to a list if the condition holds.
In this article, I’ll show you four methods of how to accomplish this goal. All four methods are generally applicable—and you can easily customize them to your specific application.
Let’s have a quick overview of the four methods in our interactive code shell:
https://trinket.io/embed/python/02d2d186a2
Exercise: Run the code for both and conditions. Are all methods semantically equivalent?
Method 1: One-Liner If Statement
The first is also the most straightforward method: if you want a one-liner without an else statement, just write the if statement in a single line! There are many tricks (like using the semicolon) that help you create one-liner statements. But for an if body with only one statement, it’s just as simple as avoiding the line break.
This method is perfectly valid and you could see it in practice. Yet, I have to mention that it “violates” the PEP8 standard (multiple statements in a single line). Therefore, you shouldn’t consider this to be Pythonic code (there are worse things under the sun though).
Method 2: Ternary with Throw-Away Else Branch
Sure, you can also use the ternary operator:
![[Image: ternary_general-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-1024x576.jpg)
If you need a quick refresher on the ternary operator, check out my detailed blog article.The ternary operator is commonly used to conditionally assign values. But you can also throw away the return value by not assigning the result to any variable. In this case, it doesn’t matter if you use or any other “dummy” return value as the result of the else branch:
It’s readable, short, and concise and I like this (well, I may be a bit biased as author of the book Python One-Liners). Sure, people will ask why you didn’t write it in multiple lines. But where is the fun there?
Method 3: Ternary with Default Value for Assignment
If you need to assign a value conditionally to a variable, but you want to do so without an else branch, you can do the following:
If the condition does not hold, the “dummy” value is assigned to the variable.
Method 4: Short Circuiting
This method I like most. It uses a Python optimization called “short circuiting” for Boolean operators: the logical operator simply returns the second operand if the first is . There’s no Boolean conversion of the second operand, it’s just returned as is.
If the first operand is, the second operand is not even evaluated.
You can use this to conditionally execute the if branch or any other code function.
There are two options:
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
Crafting beautiful Python one-liners is as much an art as it is a science. In this tutorial, you’ll learn how to compress an if statement without an else branch into a single line of Python code.
Problem: What’s the one-liner equivalent of the simple if statement without an else branch?
Here’s an example:
Code:
condition = True if condition: print('hi') # hiYou may want to (i) print something, (ii) assign a value to a variable, or (iii) append an element to a list if the condition holds.
In this article, I’ll show you four methods of how to accomplish this goal. All four methods are generally applicable—and you can easily customize them to your specific application.
Let’s have a quick overview of the four methods in our interactive code shell:
https://trinket.io/embed/python/02d2d186a2
Exercise: Run the code for both
Code:
TrueCode:
FalseMethod 1: One-Liner If Statement
The first is also the most straightforward method: if you want a one-liner without an else statement, just write the if statement in a single line! There are many tricks (like using the semicolon) that help you create one-liner statements. But for an if body with only one statement, it’s just as simple as avoiding the line break.
Code:
condition = True # Method 1: One-Liner If
if condition: print('hi')
# hiThis method is perfectly valid and you could see it in practice. Yet, I have to mention that it “violates” the PEP8 standard (multiple statements in a single line). Therefore, you shouldn’t consider this to be Pythonic code (there are worse things under the sun though).
Method 2: Ternary with Throw-Away Else Branch
Sure, you can also use the ternary operator:
![[Image: ternary_general-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-1024x576.jpg)
If you need a quick refresher on the ternary operator, check out my detailed blog article.The ternary operator is commonly used to conditionally assign values. But you can also throw away the return value by not assigning the result to any variable. In this case, it doesn’t matter if you use
Code:
NoneCode:
condition = True # Method 2: Ternary with Dummy
print('hi') if condition else NoneIt’s readable, short, and concise and I like this (well, I may be a bit biased as author of the book Python One-Liners). Sure, people will ask why you didn’t write it in multiple lines. But where is the fun there?
Method 3: Ternary with Default Value for Assignment
If you need to assign a value conditionally to a variable, but you want to do so without an else branch, you can do the following:
Code:
condition = True # Method 3: Ternary with Dummy for Assignment
x = 42 if condition else NoneIf the condition does not hold, the “dummy” value
Code:
NoneMethod 4: Short Circuiting
This method I like most. It uses a Python optimization called “short circuiting” for Boolean operators: the logical
Code:
andCode:
TrueIf the first operand is
Code:
FalseYou can use this to conditionally execute the if branch
Code:
print('hi')Code:
condition = True # Method 4: Short circuiting
condition and print('hi')There are two options:
- : As the first operand isCode:
condition == True, the second operand is returned. Thus, the statementCode:Trueis executed and the stringCode:print('hi')appears on the screen.Code:hi
- : As the first operand isCode:
condition == False, the second operand is not even evaluated because the result of the logicalCode:Falseoperation isCode:andanyway. Thus, the statementCode:Falseis never executed.Code:print('hi')
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!

