DEV Community

Suifeng023
Suifeng023

Posted on

5 Python One-Liners That Will Make You Look Like a Pro

5 Python One-Liners That Will Make You Look Like a Pro

Python is famous for being readable, but it also has a secret superpower: expressiveness. Some tasks that take 10 lines in other languages can be done in a single line of Python.

Here are 5 one-liners that aren't just clever tricks — they're genuinely useful in production code.

1. Flatten a Nested List

flat = [x for sub in [[1,2],[3,4],[5,6]] for x in sub]
# [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

This uses a nested list comprehension. The order of for clauses reads left-to-right, just like nested loops.

Real use case: Flattening API responses that return arrays of arrays.

2. Reverse a Dictionary (Swap Keys and Values)

swapped = {v: k for k, v in {"a": 1, "b": 2, "c": 3}.items()}
# {1: 'a', 2: 'b', 3: 'c'}
Enter fullscreen mode Exit fullscreen mode

Real use case: Mapping status codes back to human-readable names, or building lookup tables from config dicts.

3. Find Files by Extension

import glob; files = glob.glob("/path/**/*.py", recursive=True)
Enter fullscreen mode Exit fullscreen mode

This recursively finds all .py files under a directory. The recursive=True flag enables ** pattern matching.

Real use case: Finding all test files, all config files, or all images in a project.

4. Deduplicate a List While Preserving Order

deduped = list(dict.fromkeys([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [3, 1, 4, 5, 9, 2, 6]
Enter fullscreen mode Exit fullscreen mode

This works because dict preserves insertion order (Python 3.7+). Creating a dict from the list keeps only the first occurrence of each value, then converting back to a list gives us order-preserving deduplication.

Why not set()? Because set doesn't preserve order:

list(set([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [1, 2, 3, 4, 5, 6, 9] — order lost!
Enter fullscreen mode Exit fullscreen mode

Real use case: Removing duplicate user IDs from a log while keeping chronological order.

5. Merge Multiple Dictionaries

merged = {"a": 1} | {"b": 2} | {"c": 3}
# {'a': 1, 'b': 2, 'c': 3}
Enter fullscreen mode Exit fullscreen mode

The | merge operator was introduced in Python 3.9. For older versions, use {**d1, **d2, **d3}.

If there are conflicting keys, the rightmost dictionary wins:

{"a": 1, "b": 2} | {"b": 99, "c": 3}
# {'a': 1, 'b': 99, 'c': 3}
Enter fullscreen mode Exit fullscreen mode

Real use case: Merging default config with user config with CLI overrides:

config = DEFAULTS | user_config | cli_args
Enter fullscreen mode Exit fullscreen mode

Bonus: Read an Entire File into a String

content = open("data.txt").read()
Enter fullscreen mode Exit fullscreen mode

Simple, but powerful. For large files, use the pathlib version:

from pathlib import Path
content = Path("data.txt").read_text()
Enter fullscreen mode Exit fullscreen mode

When to Use One-Liners (and When Not To)

✅ Use them when:

  • The logic is straightforward and well-known
  • It improves readability over the multi-line alternative
  • Your team is familiar with Python idioms

❌ Avoid them when:

  • You need to squint to understand what's happening
  • Error handling is important (one-liners can't easily catch exceptions)
  • A junior developer would have no idea what the code does

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian Kernighan

Want More?

I write about Python tips, backend architecture, and developer productivity every week. Follow me so you don't miss the next one.

What's your favorite Python one-liner? Share it in the comments! 👇

Top comments (0)