DEV Community

Cover image for 7 Python One-Liners That Replace 20 Lines of Code
MaxxMini
MaxxMini

Posted on

7 Python One-Liners That Replace 20 Lines of Code

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]
Enter fullscreen mode Exit fullscreen mode

After:

result = {**defaults, **overrides}  # Python 3.5+
# Or even cleaner in 3.9+:
result = defaults | overrides
Enter fullscreen mode Exit fullscreen mode

💡 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)
Enter fullscreen mode Exit fullscreen mode

After:

result = list(dict.fromkeys(item.name.upper() for item in data if item.is_active))
Enter fullscreen mode Exit fullscreen mode

💡 dict.fromkeys() preserves insertion order while deduplicating — no need for a separate seen set.

3. Multiple Variable Swap (Replace 4 Lines)

Before:

temp = a
a = b
b = c
c = temp
Enter fullscreen mode Exit fullscreen mode

After:

a, b, c = b, c, a
Enter fullscreen mode Exit fullscreen mode

💡 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
Enter fullscreen mode Exit fullscreen mode

After:

value = config.get("database", {}).get("connection", {}).get("timeout", 30)
Enter fullscreen mode Exit fullscreen mode

💡 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)
Enter fullscreen mode Exit fullscreen mode

After:

flat = [item for sublist in nested for item in sublist]
# Or using itertools:
from itertools import chain
flat = list(chain.from_iterable(nested))
Enter fullscreen mode Exit fullscreen mode

💡 chain.from_iterable is 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)
Enter fullscreen mode Exit fullscreen mode

After:

from collections import defaultdict
groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)
Enter fullscreen mode Exit fullscreen mode

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)}
Enter fullscreen mode Exit fullscreen mode

💡 defaultdict is the pragmatic choice. groupby is 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()]
Enter fullscreen mode Exit fullscreen mode

After:

data = Path("data.txt").read_text().splitlines()
Enter fullscreen mode Exit fullscreen mode

💡 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 itertools patterns
  • 🔧 String manipulation — regex, f-strings, and encoding tricks
  • 📊 CollectionsCounter, defaultdict, namedtuple power 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)