π 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)