๐ Hidden Gems in Python You Might Not Know About
One of the things I love about Python is that itโs full of little tricks and hidden gems that can make your code cleaner, shorter, and more elegant. Recently, I asked: โWhatโs your favorite Python trick or โhidden gemโ that not many developers know about?โ โ and here are some gems worth sharing!
*1. zip()
for Parallel Iteration
*
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
โก๏ธ Perfect for looping through multiple lists at once.
2. any()
and all()
for Cleaner Checks
nums = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in nums)) # True
print(any(n > 5 for n in nums)) # True
โก๏ธ Much nicer than writing long for
loops!
3. Dictionary Merging (Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b # {'x': 1, 'y': 3, 'z': 4}
โก๏ธ A clean one-liner for combining dictionaries.
4. Quick Frequency Counts with collections.Counter
from collections import Counter
text = "banana"
print(Counter(text)) # Counter({'a': 3, 'n': 2, 'b': 1})
โก๏ธ Super useful for text processing and analysis.
5. The Walrus Operator (:=
)
if (n := len("OpenAI")) > 3:
print(f"String length is {n}")
โก๏ธ Assign and use a variable in one expression.
6. Conditional List Comprehensions
evens = [x for x in range(20) if x % 2 == 0]
โก๏ธ Compact and readable filtering.
7. Unpacking with *
nums = [1, 2, 3, 4, 5]
first, *middle, last = nums
print(first, middle, last) # 1 [2, 3, 4] 5
โก๏ธ Great for splitting sequences into meaningful parts.
๐ก Your Turn
These are just a handful of Python tricks โ but I know there are many more out there.
๐ Whatโs YOUR favorite Python hidden gem that makes you smile when you use it?
Top comments (0)