9 Fabulous Python Tricks That Make Your Code More Elegant
From clever one-liners to lesser-known built-ins, these Python techniques will help you write cleaner, faster, and more expressive code…

Great Python code isn’t just functional — it’s beautiful. And these 9 tricks prove it.
9 Fabulous Python Tricks That Make Your Code More Elegant
From clever one-liners to lesser-known built-ins, these Python techniques will help you write cleaner, faster, and more expressive code like a true pro.
If you’ve been coding in Python for a while, chances are you’ve fallen in love with its simplicity and readability.
But Python also has a deep bag of tricks — some powerful, others elegant, and a few just downright satisfying to use.
In this post, I’ll walk you through 9 advanced Python tricks that not only enhance your productivity but also make your code more elegant, expressive, and Pythonic.
Let’s dive in.
1. Use else
with Loops (Yes, Really)
Most developers use else
with if
, but did you know Python allows else
blocks with for
and while
loops?
def find_prime(nums):
for n in nums:
if n % 2 == 0:
print(f"{n} is not prime.")
break
else:
print("All numbers are odd and maybe prime!")
find_prime([3, 5, 7]) # All numbers are odd and maybe prime!
Theelse
block only executes if the loop didn't encounter abreak
. Great for search or validation use-cases.
2. Tuple Unpacking in Loops and Assignments
Tuple unpacking isn’t just for swapping values. It makes your code cleaner wherever multiple values are returned or stored.
pairs = [(1, 2), (3, 4), (5, 6)]
for a, b in pairs:
print(f"a = {a}, b = {b}")
Or even:
a, *middle, b = [1, 2, 3, 4, 5]
print(middle) # [2, 3, 4]
It makes iteration, unpacking, and pattern matching intuitive and readable.
3. Use collections.defaultdict
to Simplify Dictionary Logic
Instead of writing multiple lines to check and initialize dictionary keys, use defaultdict
.
from collections import defaultdict
word_count = defaultdict(int)
for word in ["apple", "banana", "apple"]:
word_count[word] += 1
Avoids messy if key in dict
checks. Cleaner and more concise.
4. Chaining Comparisons Like a Boss
Python lets you write chained comparisons naturally, just like in mathematics.
x = 5
if 1 < x < 10:
print("x is between 1 and 10")
Makes conditionals easier to read and closer to how we think logically.
5. The Power of the Walrus Operator (:=
)
Introduced in Python 3.8, the walrus operator lets you assign and evaluate in a single expression.
if (n := len("Python")) > 5:
print(f"String is too long ({n} characters)")
Reduces redundancy and keeps logic compact without losing clarity.
6. Context Managers Beyond with open()
You know with open(...)
already—but you can use context managers for many resources, and even write your own.
from contextlib import suppress
with suppress(FileNotFoundError):
with open("optional.txt") as f:
print(f.read())
Avoids noisy try-except
blocks for harmless exceptions.
7. List Comprehensions with Conditionals
List comprehensions are Pythonic — but you can go a level deeper with inline conditionals.
nums = [1, 2, 3, 4, 5]
labels = ["even" if x % 2 == 0 else "odd" for x in nums]
Keeps transformations and logic in one readable line.
8. The get()
Method with Default Values
Instead of checking whether a key exists in a dictionary, use .get()
with a fallback value.
config = {"theme": "dark"}
mode = config.get("mode", "default")
Avoids KeyError
and reduces if-else clutter.
9. Merging Dictionaries the Clean Way
Starting from Python 3.9, dictionaries can be merged beautifully:
defaults = {"theme": "light", "autosave": True}
user_prefs = {"theme": "dark"}
final_config = defaults | user_prefs
Replaces verbose update()
calls with clean and intuitive syntax.
Bonus: Embrace Pythonic Idioms
Python isn’t just a language — it’s a style. Writing elegant Python means embracing its idioms, thinking in expressions rather than instructions, and choosing clarity over cleverness.
Here’s a quick comparison:
# Not so elegant
if len(my_list) == 0:
pass
# Pythonic
if not my_list:
pass
Final Thoughts
These tricks aren’t about showing off — they’re about writing better, clearer code that others will thank you for.
Elegance in code isn’t just aesthetics — it’s a signal of thoughtfulness, experience, and craftsmanship.
If this post helped you level up your Python game, consider sharing it with your fellow devs or saving it for later!
Which of these tricks did you already know? Got one I missed?
Let’s talk Python in the comments below!
Follow me for more tips on writing cleaner, faster, and more Pythonic code.
