I review a lot of Python code. The difference between a junior and a senior often comes down to knowing these patterns.
Here are 12 one-liners I use almost daily.
1. Flatten a List of Lists
# Instead of:
result = []
for sublist in nested:
for item in sublist:
result.append(item)
# One-liner:
result = [item for sublist in nested for item in sublist]
2. Swap Two Variables
a, b = b, a
No temp variable needed. Python handles this elegantly.
3. Merge Two Dictionaries
merged = {**dict1, **dict2}
# Python 3.9+
merged = dict1 | dict2
If keys overlap, the second dict wins.
4. Read a File Into a List of Lines
lines = open('file.txt').read().splitlines()
5. Find the Most Common Element
from collections import Counter
most_common = Counter(my_list).most_common(1)[0][0]
Works with strings, numbers, any hashable type.
6. Reverse a String
reversed_str = my_string[::-1]
The [::-1] slice works on lists too.
7. Check if All Elements Meet a Condition
# Are all scores passing?
all_pass = all(score >= 60 for score in scores)
# Does any score fail?
any_fail = any(score < 60 for score in scores)
8. Create a Dictionary From Two Lists
keys = ['name', 'age', 'city']
values = ['Alex', 30, 'Berlin']
person = dict(zip(keys, values))
9. Remove Duplicates While Preserving Order
unique = list(dict.fromkeys(my_list))
This preserves insertion order (Python 3.7+). Using set() loses order.
10. Transpose a Matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
11. Filter and Transform in One Step
# Get squares of even numbers only
result = [x**2 for x in numbers if x % 2 == 0]
12. Pretty-Print JSON
import json
print(json.dumps(data, indent=2, ensure_ascii=False))
The ensure_ascii=False part is crucial if you work with non-English text.
The One Rule I Follow
One-liners should make code MORE readable, not less. If a one-liner takes 30 seconds to understand, use 3 lines instead.
The goal is clarity, not cleverness.
What is your favorite Python one-liner?
I bet there are patterns I missed. Share your most-used one-liner in the comments and I will add the best ones to this list with credit.
I write about Python, web scraping, and developer productivity. Follow for weekly practical tips.
More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs
Top comments (0)