Every Python developer has that moment — you write a clean 15-line function, then a colleague rewrites it in one line that does the same thing.
These are not code golf tricks. These are real patterns I use daily that make code shorter and more readable.
1. Dictionary Merge (Replace 5 Lines)
Before:
result = {}
for key in defaults:
result[key] = defaults[key]
for key in overrides:
result[key] = overrides[key]
After:
result = {**defaults, **overrides} # Python 3.5+
# Or even cleaner in 3.9+:
result = defaults | overrides
💡 The
|operator also works with|=for in-place merge.
2. Conditional List Building (Replace 8 Lines)
Before:
result = []
for item in data:
if item.is_active:
transformed = item.name.upper()
if transformed not in seen:
seen.add(transformed)
result.append(transformed)
After:
result = list(dict.fromkeys(item.name.upper() for item in data if item.is_active))
💡
dict.fromkeys()preserves insertion order while deduplicating — no need for a separateseenset.
3. Multiple Variable Swap (Replace 4 Lines)
Before:
temp = a
a = b
b = c
c = temp
After:
a, b, c = b, c, a
💡 Python evaluates the entire right side before assigning. Works with any number of variables.
4. Nested Dictionary Access (Replace Try/Except)
Before:
try:
value = config["database"]["connection"]["timeout"]
except KeyError:
value = 30
After:
value = config.get("database", {}).get("connection", {}).get("timeout", 30)
💡 The chained
.get()pattern is safer than try/except and more explicit about the default.
5. Flatten Nested Lists (Replace Loops)
Before:
flat = []
for sublist in nested:
for item in sublist:
flat.append(item)
After:
flat = [item for sublist in nested for item in sublist]
# Or using itertools:
from itertools import chain
flat = list(chain.from_iterable(nested))
💡
chain.from_iterableis lazy — better for large datasets. The comprehension is better for readability.
6. Group By Key (Replace 6 Lines)
Before:
groups = {}
for item in items:
key = item.category
if key not in groups:
groups[key] = []
groups[key].append(item)
After:
from collections import defaultdict
groups = defaultdict(list)
for item in items:
groups[item.category].append(item)
Or as a true one-liner with itertools:
from itertools import groupby
groups = {k: list(v) for k, v in groupby(sorted(items, key=lambda x: x.category), key=lambda x: x.category)}
💡
defaultdictis the pragmatic choice.groupbyis elegant but requires sorted input.
7. File Read + Process (Replace 4 Lines)
Before:
f = open("data.txt")
lines = f.readlines()
f.close()
data = [line.strip() for line in lines if line.strip()]
After:
data = Path("data.txt").read_text().splitlines()
💡
Path.read_text()handles opening and closing automatically. Cleaner than context managers for simple reads.
These 7 Are Just the Start
I compiled 50 Python one-liners that I use in production code — not just the basics, but advanced patterns for:
- 🧮 Data processing — comprehensions, generators, and
itertoolspatterns - 🔧 String manipulation — regex, f-strings, and encoding tricks
- 📊 Collections —
Counter,defaultdict,namedtuplepower moves - 🚀 Performance — lazy evaluation, caching, and memory-efficient patterns
- 🛡️ Error handling — graceful one-liner patterns that don't sacrifice readability
Each one-liner comes with:
- ✅ The verbose version it replaces
- ✅ When to use it vs when to keep it verbose
- ✅ Python version requirements
- ✅ Performance notes
More by MaxMini
🛠️ 27+ Free Developer Tools — JSON formatter, UUID generator, password analyzer, and more. All browser-based, no signup.
🎮 27 Browser Games — Built with vanilla JS. Play instantly, no install.
📚 Developer Resources on Gumroad — AI prompt packs, automation playbooks, and productivity guides.
💰 DonFlow — Free budget tracker. Plan vs reality, zero backend.
More Developer Resources
Built with DonFlow — a zero-server budget planner that runs entirely in your browser.
Top comments (0)