DEV Community

Jenni Juli
Jenni Juli

Posted on

๐Ÿ Hidden Gems in Python You Might Not Know About

๐Ÿ 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}")
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ 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
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ 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}
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ 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})
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ Super useful for text processing and analysis.


5. The Walrus Operator (:=)

if (n := len("OpenAI")) > 3:
    print(f"String length is {n}")
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ Assign and use a variable in one expression.


6. Conditional List Comprehensions

evens = [x for x in range(20) if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ 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
Enter fullscreen mode Exit fullscreen mode

โžก๏ธ 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)