9 Underrated Python Tricks That Will Blow Your Mind
Stuff You Should Have Learned After Your First Year Writing Python (But Probably Didn’t)
I remember the exact moment Python humbled me.
I’d been writing it professionally for years. Deployed services. Shipped features. Mentored juniors. Felt… comfortable.
Then a teammate rewrote one of my “perfectly fine” utility functions in three lines. It ran faster. Read cleaner.
And made me quietly angry in the best possible way.
That’s when it hit me: most Python developers stop learning Python way too early.
We learn syntax. Then frameworks. Then libraries.
And we never come back to the language itself.
This article is for that version of you.
Not beginner tricks. Not academic trivia.
These are underrated Python tools I’ve seen quietly change how good developers write code.
Tools that save time, reduce bugs, and make your code look like you know what you’re doing.
1. for/else Is Not Weird — You Just Never Gave It a Chance
Most people hear about for/else and immediately distrust it. Fair. It looks wrong.
But it’s brilliant when you stop fighting it.
for user in users:
if user.id == target_id:
process(user)
break
else:
raise ValueError("User not found")The else runs only if the loop didn’t break.
- No flags
- No duplicated logic
- No accidental fall-through
I use this whenever I’m searching for something and failure matters.
If you’ve ever written a found = False variable, this is your sign to delete it.
Reference: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements
2. dict.setdefault() Is a Gateway Drug (to Cleaner Code)
You’ve written this. I know you have.
if key not in data:
data[key] = []
data[key].append(value)Stop it.
data.setdefault(key, []).append(value)That’s it. One line. Same behavior.
This shines when
- Grouping values
- Building indexes
- Parsing data streams
Is defaultdict better sometimes? Yes.
Is setdefault() criminally underused? Also yes.
Use it when you don’t want to change the data structure type but still want elegance.
3. enumerate() Prevents Off-by-One Bugs You Don’t See Coming
Any time I see this
for i in range(len(items)):
print(i, items[i])I flinch.
Here’s the grown-up version
for i, item in enumerate(items):
print(i, item)Even better
for i, item in enumerate(items, start=1):
print(f"{i}. {item}")Why it matters
- Cleaner intent
- Fewer index mistakes
- Easier refactors
This is not just style. It’s defensive programming.
4. Tuple Unpacking Is a Power Move
You don’t need temporary variables.
You need confidence.
a, b = b, aYes, that’s a swap. No temp variable. Python handles it safely.
But it goes deeper
(x1, y1), (x2, y2) = point_a, point_bOr this beauty
first, *middle, last = itemsI use this constantly when
- Parsing function returns
- Cleaning up messy data
- Writing readable APIs
If your code feels cluttered, unpacking usually fixes it.
5. any() and all() Replace Ugly Boolean Soup
I used to write this
valid = False
for item in items:
if item.is_valid():
valid = True
breakWhy? Habit. Fear. Lack of caffeine.
Get Rishikant Sharma’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s the adult version
valid = any(item.is_valid() for item in items)And the sibling
all_ready = all(task.ready for task in tasks)Readable. Efficient. Expressive.
If your condition reads like a sentence, you’re doing it right.
6. zip() Is the Most Underappreciated Data Tool in Python
Pairing related data? Stop indexing manually.
for name, score in zip(names, scores):
print(name, score)It also shines for transformations
combined = dict(zip(keys, values))And comparisons
for prev, curr in zip(data, data[1:]):
check_delta(prev, curr)Once you start seeing zip(), you’ll see it everywhere.
7. Context Managers (with) Are About More Than Files
Most people think with equals files.
That’s thinking small.
Anything that needs setup and teardown belongs in a context manager
- Locks
- Database connections
- Timers
- Feature flags
Real example I use
with timed("expensive_call"):
run_job()It guarantees cleanup. Even on exceptions.
If you care about reliability, learn to write your own context managers.
Reference: https://docs.python.org/3/library/contextlib.html
8. __repr__ Is a Debugging Superpower
If your objects print like this
<Thing object at 0x104af...>You’re making debugging harder than it needs to be.
Do this
class User:
def __repr__(self):
return f"User(id={self.id}, email={self.email})"Suddenly
- Logs are readable
- Debuggers are useful
- You trust your objects
I consider __repr__ mandatory in any serious class.
9. Small Functions Beat Clever Code (Every Time)
This isn’t syntax. It’s philosophy.
Python rewards clarity.
If a function
- Does one thing
- Fits on one screen
- Has a boring name
You’re winning.
I’ve never regretted breaking code apart.
I’ve often regretted being clever.
That’s the trick no one talks about.
Finally (And a Slightly Opinionated Take)
Python doesn’t reward brilliance.
It rewards taste.
The developers who stand out aren’t the ones writing wizard code. They’re the ones writing code you trust at 2pm and 2am.
If even one of these tricks made you rethink how you write Python, this was worth your time.
If you disagreed with something? Even better.
Let’s talk.
Drop a comment. Argue with me. Clap if this helped.
Or send it to that teammate who still uses range(len(...)).
And maybe — just maybe — save this for later. You’ll come back to it.









