# 8 Useful Python One-Liners You Ought to Know

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

## 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
[line.strip() for line in open(filename)]``````

## Factorial Python One-Liner

``````# Factorial Python One-Liner
reduce(lambda x, y: x * y, range(1, n+1))``````

## Fibonacci Python One-Liner

``````# Fibonacci Python One-Liner
lambda x: x if x<=1 else fib(x-1) + fib(x-2)``````

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

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