I’m not only a one-liner fan–I’m a fanatic. In this blog post, I’ll show you the most impressive Python one-liners. You can pack almost everything into a single line of Python code!
This blog article only uses Python one-liners that I created my self for my Python One-Liners book and as a contributor to the official Python wiki. For each one-liner, I’ve also written a detailed blog article with video—so feel free to click on the explainer resource after the code of each one-liner to learn more!
Palindrome Python One-liner
# Palindrome Python One-Liner phrase.find(phrase[::-1])
Read More: Palindrome One-Liner
Swap Two Variables Python One-Liner
# Swap Two Variables Python One-Liner a, b = b, a
Read More: Swap Two Variables One-Liner
Sum Over Every Other Value One-Liner
# Sum Over Every Other Value Python One-Liner sum(stock_prices[::2])
Read More: Sum Over Every Other Value One-Liner
Read File Python One-Liner
# Read File Python One-Liner [line.strip() for line in open(filename)]
Read More: Read File One-Liner
Factorial Python One-Liner
# Factorial Python One-Liner reduce(lambda x, y: x * y, range(1, n+1))
Read More: Factorial One-Liner
Fibonacci Python One-Liner
# Fibonacci Python One-Liner lambda x: x if x<=1 else fib(x-1) + fib(x-2)
Read More: Fibonacci One-Liner
Quicksort Python One-Liner
# Quicksort Python One-liner lambda L:  if L== else qsort([x for x in L[1:] if x< L]) + L[0:1] + qsort([x for x in L[1:] if x>=L])
Read More: Quicksort One-Liner
Sieve of Eratosthenes Python One-Liner
# Sieve of Eratosthenes Python One-liner reduce( (lambda r,x: r-set(range(x**2,n,x)) if (x in r) else r), range(2,int(n**0.5)), set(range(2,n)))
Read More: Sieve One-Liner
Get the Book Python One-Liners
But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).