Python one-liners are Turing complete since Python is a Turing-complete language and any Python program can be executed as a one-liner using the
exec() function, by enclosing the entire program in a string and passing it to
In this article, I slowly build this argument and also provide less “brute-force” ways to build Python One-Liners than just packing it into the
exec() function. 😉
What Are Python One-Liners?
Before we delve into the question of Turing completeness, let’s take a closer look at what Python one-liners are and how they work.
💡 A Python one-liner is a single line of code that performs a specific task or computation. One-liners are often used for simple tasks such as printing a message to the console or performing basic arithmetic operations, but they can also be used for more complex tasks such as file manipulation, data analysis, and web scraping.
One of the benefits of Python one-liners is their simplicity and ease of use. Since they are typically only a single line of code, they can be quickly typed into the Python interpreter or added to a script without the need for complex code formatting or file organization.
How to Write Python One-Liners?
Python one-liners can be written in various ways, depending on the specific task you want to accomplish.
Here are a few examples of how multiple lines of Python code can be expressed as a single line using semicolons and parentheses:
# Multiple print statements print("Hello") print("World") # One-liner equivalent print("Hello"); print("World") # Multiple arithmetic operations x = 1 + 2 y = 3 * 4 z = x + y # One-liner equivalent z = (1 + 2) + (3 * 4) # Multiple if statements if x > y: print("x is greater than y") elif y > x: print("y is greater than x") else: print("x and y are equal") # One-liner equivalent print("x is greater than y" if x > y else "y is greater than x" if y > x else "x and y are equal")
As you can see, these examples demonstrate how multiple lines of code can be expressed as a single line using semicolons and parentheses to separate and group statements as needed.
Turing Completeness and Python One-Liners
Now let’s get back to the original question: are Python one-liners Turing complete?
The answer is yes: any program that can be computed by a Turing machine can also be expressed as a Python one-liner.
This may seem like a bold claim, but it is actually a consequence of the fact that Python is a Turing-complete language. This means that any computation that can be expressed in a step-by-step process can also be computed using Python, including complex algorithms, data structures, and user interfaces.
While it may not always be practical or advisable to express large and complex programs as one-liners, the fact remains that Python one-liners have the full expressive power of the Python language at their disposal.
Furthermore, since Python is a Turing-complete language, any program that can be computed by a Turing machine can also be expressed as a Python one-liner, provided that the line length limit is not exceeded.
But how exactly can a multi-liner be expressed as a one-liner?
The answer lies in using semicolons and parentheses to separate and group statements as needed. I also provide a more generalized solution on how to convert any multi-liner to a one-liner afterward.
Here’s an example of a multi-liner that calculates the sum of the squares of the first ten positive integers:
sum = 0 for i in range(1, 11): sum += i**2 print(sum)
To express this as a one-liner, we can use semicolons to separate the statements and parentheses to group the loop expression:
sum = 0; [sum := sum + i**2 for i in range(1, 11)]; print(sum)
In this example, the semicolons are used to separate the three statements (assigning the initial value of
sum, calculating the sum of squares using a list comprehension, and printing the result). The list comprehension expression is enclosed in square brackets and is separated from the other statements using semicolons. Finally, the entire expression is terminated with a semicolon.
While this example may not be as readable or maintainable as the original multi-liner, it demonstrates how a complex computation can be expressed as a concise and efficient one-liner using Python.
💡 Recommended: How to Execute Multiple Lines in a Single Line Python From Command-Line?
In addition to using semicolons and parentheses to separate and group statements, the Python
exec() function can also be used to express any Python program as a one-liner. The
exec() function allows a Python program to be executed from a string, rather than a separate file.
To see how this works, let’s consider an example. Here’s a multi-liner that calculates the factorial of a given integer:
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(5))
To express this as a one-liner using
exec(), we can first use triple quotes to enclose the entire program in a string. We can then pass this string to the
exec() function to execute the program:
exec('''def factorial(n):\n return 1 if n == 0 else n * factorial(n-1)\nprint(factorial(5))''')
In this example, the
exec() function executes the entire program contained within the triple-quoted string. The function definition and the call to
print() are separated by a newline character within the string, which allows the entire program to be executed as a single line.
This demonstrates how any Python program can be expressed as a one-liner using the
exec() function. However, it’s important to note that this approach can be less readable and maintainable than using multiple lines of code. It’s generally recommended to use one-liners only for simple and concise computations, and to use multiple lines of code for more complex programs that require more structure and organization.
💡 Recommended: Python exec() — A Hacker’s Guide to A Dangerous Function
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.
Get your Python One-Liners on Amazon!!
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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.