7 Python One-Liners that will Blow Your Mind

Less is more?

Photo by Photos by Lanty from Unsplash

The term one-liner comes from comedy where a joke is delivered in a single line. A good one-liner is said to be meaningful and concise. This concept also exists in programming. Python one-liners are short programs that can perform powerful operations. It’s nearly impossible in other languages like Java, so it’s considered as a Pythonic feature.

Arguments about Python one-liners

If it’s your first time seeing one-liners, please remember Python one-liner is a double-edged sword. On one hand, it makes code look cool and it’s definitely a way to impress your colleagues or interviewers. But on the other hand, a fancy one-liner can be confusing and difficult to understand and turn into a way to show off your skills. Thus, do expect some arguments during the code review. As a rule of thumb, one-liners are very welcomed in Python, but if it goes too far and starts to confuse people, then it’s the moment to drop it. Eventually, your code needs to be readable and maintainable.

Anyway, in this article, I want to give you some practical examples of Python one-liners that can boost your code quality. And I will also show you some fancy one-liners to have fun with. In any case, you must know all the possible ways of expressing your thoughts in code so that you can make the right decision.

Swap two variables

# normal
c = a
a = b
b = c# 1-liner
a,b = b,a

In a normal situation, when you swap two variables, you need a middle-man in between. I also mentioned this trick in my How to Write Pythonic Code article. In Python, you can do it in one line. The right side is an expression that is actually a tuple (b,a) and the left side is variables that represent the first and second variable in the tuple.

List comprehension

result = []
for i in range(10):
result.append(i**2)# use list comprehension
result = [i**2 for i in range(10)]

This is another Pythonic feature I put in my previous article. It tells Python what to do with each element in the list. The list contains both for and if statements. For example:

#list comprehension with if
result = [i**2 for i in range(10) if i%2==0]#read file in one-line
[line.strip() for line in open(filename)]

List/Set comprehension is such a powerful tool that everyone must know it. It allows you to write code that’s elegant and almost as easy to read as plain English. Each list comprehension includes 3 elements: 1) expression. Any valid expression like i**2 or line.strip(). 2) member. The object in the iterable. 3) iterable. A list, set, generator, or any other iterable object.

Lambda and Map functions

The next level of list comprehension is the lambda function. Check out Learn Python Lambda from Scratch.

Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.

# traditional function with def
def sum(a, b):
return a + b# lambda function with name
sum_lambda = lambda x, y: x + y

Lambda functions are normally combined with Python higher-order functions. There are a couple of built-in higher-order functions like map, filter, reduce, sorted, sum, any, all .

map(lambda x:x**2, [i for i in range(3)]) 
# <map object at 0x105558a90>filter(lambda x: x % 2 == 0, [1, 2, 3])
# <filter object at 0x1056093d0>from functools import reduce
reduce(lambda x, y: x + y, [1, 2, 3])
# 6

It is worth noting that the return of map and filter are objects, not the result of the function. If you want to get the actual result, you need to convert it to a list like list(map(lambda x:x**2, [i for i in range(3)]).

Print without newlines

print is one of the most basic statements in every programming language. But have you ever read the definition of print interface in Python doc?

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The function prints objects, separated by sep and followed by end. So let’s look at this one-liner.

#for-loop
for i in range(1,5):
print(i, end=" ")#one-liner
print(*range(1,5)) #1 2 3 4

Since print accepts an iterable, we can directly use *range(1,5) as the input and it has the same output as the for loop.

Walrus

Walrus operator is a feature since Python 3.8. It gives you a new syntax := for assignment variables in the middle of expressions. It is to avoid calling the same function twice.

This is an example from Python doc. Instead of having a separate line to calculate mo upfront, walrus operator allows you to calculate it on the flight.

# without walrus
discount = 0.0
mo = re.search(r'(\d+)% discount', "10% discount")
if mo:
discount = float(mo.group(1))/100.0# with walrus
discount = 0.0
if (mo := re.search(r'(\d+)% discount', "10% discount")):
discount = float(mo.group(1)) / 100.0

But I find walrus quite useful in the for/while loop because the code looks really neat and just like normal English.

# without walrus
f = open("source/a.txt")
line = f.readline()
while line != '':
print(line)
line = f.readline()# with walrus
f = open("f.txt")
while (line := f.readline()) != '':
print(line)

Fibonacci

Alright, now let’s checkout some fancy examples. Do you know you can actually code Fibonacci algorithm in one line? It’s pretty amazing!

#for-loop
def fib(x):
if x <= 2:
return 1
return fib(x - 1) + fib(x - 2)#1-liner
fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)

Quicksort

If you think you can still handle it, let’s see the next level of one-liner. Here is the one-liner version of quick sort, a famous sorting 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 []
q([])

In my opinion, it’s fun to look at it and understand how powerful Python is, but don’t use it in your work. When one-liner gets too long to fit in one line, it’s time to drop it.

Conclusion

As usual, I hope you find this article useful and learned a new way to improve your code quality. Feel free to share your experience with one-liners. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.