Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a while loop in a single line of code? This article explores this mission-critical question in all detail.
How to Write a While Loop in a Single Line of Python Code?
There are three ways of writing a one-liner while loop:
- Method 1: If the loop body consists of one statement, write this statement into the same line:
while True: print('hi'). This prints the string
'hi'to the shell for as long as you don’t interfere or your operating system forcefully terminates the execution.
- Method 2: If the loop body consists of multiple statements, use the semicolon to separate them:
while True: print('hi'), print('bye'). This runs the statements one after the other within the while loop.
- Method 3: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator:
while True: print('hi') if condition else print('bye').
Exercise: Run the code. What do you observe? Try to fix the infinite loop!
Next, you’ll dive deep into each of these methods and become a better coder in the process.
Before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
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!
But enough promo, let’s dive into the first method—the profane…
Method 1: Single-Statement While Loop One-Liner
Just writing the while loop into a single line of code is the most direct way of accomplishing the task. Say, you want to write the following infinite while loop in a single line of code:
while True: print('hi') ''' hi hi ... '''
You can easily get this done by writing the command in a single line of code:
# Method 1: Single-Line While Loop while True: print('hi')
While this answer seems straightforward, the interesting question is: can we write a more complex while loop that has a longer loop body in a single line?
Related Article: If you’re interested in compressing whole algorithms into a single line of code, check out this article with 10 Python one-liners that fit into a single tweet.
Let’s explore an alternative Python trick that’s very popular among Python masters:
Method 2: Multi-Statement While Loop One-Liner
As it turns out, you can also use the semicolon to separate multiple independent statements and express them in a single line. The statement
expression1; expression2 reads “first execute
expression1, then execute
Here’s an example how you can run a while loop until a counter variable
c reaches the threshold
c == 10:
c = 0 while c < 10: print(c); c = c + 1 ''' 0 1 2 3 4 5 6 7 8 9 '''
This way, you can easily compress “flat” loop bodies in a single line of Python code.
But what if the loop body is not flat but nested in a hierarchical manner—how to express those nested while loops in a single line?
Method 3: Nested Compound Statements While Loop One-Liner
You often want to use compound statements in Python that are statements that require an indented block such as if statements or while loops.
In the previous methods, you’ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements.
Problem: But what if you want to use a compound statement within a simple while loop—in a single line of code?
Example: The following statement works just fine:
# YES: if expression: print('hi')
You can also add multiple statements like this:
# YES: if expression: print('hi'); print('ho')
But you cannot use nested compound statements in a while loop one-liner:
# NO: while expression1: if expression2: print('hi')
Python throws an error does not work because both the
if statements are compound.
However, there’s an easy fix to make this work. You can replace the
if expression2: print('hi') part with a ternary operator and use an expression rather than a compound statement:
# Method 3: One-Line While Loop + Ternary Operator while True: print('yes') if True else print('no')
You can also use nested ternary operators to account for possibly nested if blocks:
Related Video: One-Line For Loop
Where to Go From Here
Knowing small Python one-liner tricks such as the list comprehension and single-line for loops 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.
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 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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.