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])]
Usage:
nested = [1, [2, 3], [4, [5, 6]], 7]
print(flatten(nested)) # [1, 2, 3, 4, 5, 6, 7]
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'
Bonus — palindrome checker:
is_palindrome = lambda s: s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
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]
Usage:
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(most_common(words)) # 'apple'
No loops, no dictionaries. Counter does all the heavy lifting.
4. Transpose a Matrix
transpose = lambda matrix: list(map(list, zip(*matrix)))
Usage:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(transpose(matrix))
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
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))
Usage:
data = [3, 5, 2, 5, 3, 8, 1, 2, 7]
print(dedupe(data)) # [3, 5, 2, 8, 1, 7]
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()
Even better — list of non-empty lines:
lines = [l for l in open("file.txt") if l.strip()]
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}
Usage:
defaults = {"theme": "dark", "lang": "en"}
user_prefs = {"lang": "zh", "fontsize": 14}
config = {**defaults, **user_prefs}
print(config) # {'theme': 'dark', 'lang': 'zh', 'fontsize': 14}
The ** unpacking operator merges dictionaries with later values overriding earlier ones. Clean and readable.
Python 3.9+ alternative:
config = defaults | user_prefs
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)}
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'}]}
Why One-Liners Matter
These aren't just party tricks. They demonstrate:
- Deep Python knowledge — You understand the language's power features
- Less code = fewer bugs — Concise code has fewer places to go wrong
- Better readability — Once you learn these patterns, they're instantly recognizable
- 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)