DEV Community

Suifeng023
Suifeng023

Posted on

7 Python One-Liners That Will Make You Look Like a Senior Developer

7 Python One-Liners That Will Make You Look Like a Senior Developer

You don't need 50 lines of code to do powerful things in Python. These one-liners will change how you write code forever.

Every senior Python developer has a bag of tricks — concise, elegant solutions that do in one line what takes beginners a whole function. Today I'm sharing my favorite 7 Python one-liners that demonstrate deep language understanding.


1. Flatten Any Nested List

flatten = lambda x: [i for e in x for i in (flatten(e) if isinstance(e, list) else [e])]
Enter fullscreen mode Exit fullscreen mode

Usage:

nested = [1, [2, 3], [4, [5, 6]], 7]
print(flatten(nested))  # [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Works with any depth of nesting. This recursive lambda is a Pythonic masterpiece.


2. Reverse a String (or Any Sequence)

reversed_text = "Hello World"[::-1]  # 'dlroW olleH'
Enter fullscreen mode Exit fullscreen mode

Bonus — palindrome checker:

is_palindrome = lambda s: s == s[::-1]
print(is_palindrome("racecar"))  # True
print(is_palindrome("hello"))    # False
Enter fullscreen mode Exit fullscreen mode

Python's slice syntax [start:stop:step] with -1 step is the cleanest way to reverse anything.


3. Find the Most Frequent Element

from collections import Counter
most_common = lambda lst: Counter(lst).most_common(1)[0][0]
Enter fullscreen mode Exit fullscreen mode

Usage:

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(most_common(words))  # 'apple'
Enter fullscreen mode Exit fullscreen mode

No loops, no dictionaries. Counter does all the heavy lifting.


4. Transpose a Matrix

transpose = lambda matrix: list(map(list, zip(*matrix)))
Enter fullscreen mode Exit fullscreen mode

Usage:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(transpose(matrix))
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Enter fullscreen mode Exit fullscreen mode

The *matrix unpacks rows as separate arguments to zip(), which then regroups them by column. Elegant.


5. Remove Duplicates While Preserving Order

dedupe = lambda lst: list(dict.fromkeys(lst))
Enter fullscreen mode Exit fullscreen mode

Usage:

data = [3, 5, 2, 5, 3, 8, 1, 2, 7]
print(dedupe(data))  # [3, 5, 2, 8, 1, 7]
Enter fullscreen mode Exit fullscreen mode

Why not set()? Because set() destroys order. dict.fromkeys() has been insertion-ordered since Python 3.7. This is the fastest, most Pythonic way.


6. Read a File into a Single String

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

Even better — list of non-empty lines:

lines = [l for l in open("file.txt") if l.strip()]
Enter fullscreen mode Exit fullscreen mode

For production code, always use with open(...), but for quick scripts and one-liners, this is a lifesaver.


7. Merge Multiple Dictionaries

merged = {**dict1, **dict2, **dict3}
Enter fullscreen mode Exit fullscreen mode

Usage:

defaults = {"theme": "dark", "lang": "en"}
user_prefs = {"lang": "zh", "fontsize": 14}
config = {**defaults, **user_prefs}
print(config)  # {'theme': 'dark', 'lang': 'zh', 'fontsize': 14}
Enter fullscreen mode Exit fullscreen mode

The ** unpacking operator merges dictionaries with later values overriding earlier ones. Clean and readable.

Python 3.9+ alternative:

config = defaults | user_prefs
Enter fullscreen mode Exit fullscreen mode

Bonus: The "Swiss Army Knife" One-Liner

# Group a list by a key function
from itertools import groupby
group = lambda lst, key: {k: list(g) for k, g in groupby(sorted(lst, key=key), key)}
Enter fullscreen mode Exit fullscreen mode
students = [
    {"name": "Alice", "grade": "A"},
    {"name": "Bob", "grade": "B"},
    {"name": "Charlie", "grade": "A"},
]
by_grade = group(students, lambda x: x["grade"])
# {'A': [{'name': 'Alice', 'grade': 'A'}, {'name': 'Charlie', 'grade': 'A'}], 'B': [{'name': 'Bob', 'grade': 'B'}]}
Enter fullscreen mode Exit fullscreen mode

Why One-Liners Matter

These aren't just party tricks. They demonstrate:

  1. Deep Python knowledge — You understand the language's power features
  2. Less code = fewer bugs — Concise code has fewer places to go wrong
  3. Better readability — Once you learn these patterns, they're instantly recognizable
  4. Pythonic thinking — This is how Python was designed to be used

"Beautiful is better than ugly. Simple is better than complex." — The Zen of Python

Use Responsibly

One-liners are great, but don't sacrifice readability for brevity. If a one-liner takes 30 seconds to understand, write it as a proper function with a clear name. Code is read far more often than it's written.

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

Top comments (0)