10 Python One-Liners That Replace 50 Lines of Code
Cut the clutter, write cleaner code, and master these powerful one-liners that make your Python scripts shorter, faster, and more elegant.

Stop Writing Boilerplate — Let Python Do the Heavy Lifting for You
10 Python One-Liners That Replace 50 Lines of Code
If your Python scripts look like mini-novels, you’re not alone.
Many developers start with verbose code that gets the job done, but over time, you realize… Python can do the same thing in a single line.
One-liners aren’t just about saving space — they often improve readability, performance, and maintainability. In fact, learning these idiomatic patterns can transform you from “someone who writes Python” to “a Pythonic problem-solver.”
Below are 10 practical Python one-liners that can replace dozens of lines of code — without sacrificing clarity.
I’ll show you the long way, then the one-liner way, so you can see the real difference.
1. Flatten a List of Lists
The verbose way:
flattened = []
for sublist in nested_list:
for item in sublist:
flattened.append(item)
The one-liner:
flattened = [item for sublist in nested_list for item in sublist]
List comprehensions can handle multiple loops — perfect for flattening nested structures.
2. Reverse a String
The verbose way:
reversed_str = ""
for char in my_string:
reversed_str = char + reversed_str
The one-liner:
reversed_str = my_string[::-1]
Python’s slicing syntax isn’t just for lists — it works beautifully for strings.
3. Count Item Frequencies
The verbose way:
frequency = {}
for item in items:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1
The one-liner:
from collections import Counter
frequency = Counter(items)
Counter
from collections
is your go-to for counting elements without boilerplate.
4. Merge Two Dictionaries
The verbose way:
merged = dict(a)
for key, value in b.items():
merged[key] = value
The one-liner (Python 3.9+):
merged = a | b
For older versions, you can use {**a, **b}
— still one line, still beautiful.
5. Read a File into a List
The verbose way:
lines = []
with open("file.txt", "r") as f:
for line in f:
lines.append(line.strip())
The one-liner:
lines = [line.strip() for line in open("file.txt")]
Just be careful with large files — one-liners don’t change memory usage patterns.
6. Find the Most Common Element
The verbose way:
frequency = {}
for item in items:
frequency[item] = frequency.get(item, 0) + 1
most_common = None
max_count = 0
for key, count in frequency.items():
if count > max_count:
most_common = key
max_count = count
The one-liner:
most_common = max(set(items), key=items.count)
Or, for efficiency with large datasets: Counter(items).most_common(1)[0][0]
.
7. Swap Two Variables
The verbose way:
temp = a
a = b
b = temp
The one-liner:
a, b = b, a
This Python tuple unpacking trick is clean, safe, and has no performance penalty.
8. Create a Dictionary from Two Lists
The verbose way:
result = {}
for i in range(len(keys)):
result[keys[i]] = values[i]
The one-liner:
result = dict(zip(keys, values))
zip
is the unsung hero of Python — combine it with dict
for instant key-value creation.
9. Filter Even Numbers
The verbose way:
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
The one-liner:
evens = [num for num in numbers if num % 2 == 0]
List comprehensions are not only shorter — they’re faster than for
loops.
10. Remove Duplicates While Preserving Order
The verbose way:
seen = set()
unique_list = []
for item in my_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
The one-liner (Python 3.7+):
unique_list = list(dict.fromkeys(my_list))
dict.fromkeys
cleverly drops duplicates while keeping the first occurrence.
Why One-Liners Matter (and When to Avoid Them)
One-liners are great for:
- Reducing boilerplate code
- Improving readability for common patterns
- Writing more “Pythonic” code
But here’s the catch — not every one-liner is good. If it sacrifices clarity for cleverness, you’re doing future-you (and your teammates) a disservice.
A good rule of thumb: if someone unfamiliar with Python would struggle to understand it in 10 seconds, consider breaking it into multiple lines.
Final Thoughts
Mastering one-liners is about more than saving space — it’s about writing code that’s clear, elegant, and expressive.
The more you use Python, the more you’ll recognize these patterns naturally. And when you do, you’ll spend less time wrestling with syntax and more time solving problems.
So, the next time you catch yourself writing five lines to do something simple, stop and ask: “Could this be a one-liner?”
Write less, do more — that’s the Pythonic way.
