Python is beautiful. But even if you’ve been using it for years, there are some hidden gems that can make your code cleaner, faster, or just more fun.
Here are 10 Python tricks that might just blow your mind 🤯 — with examples you can copy straight into your next project.
- 🥚 Walrus Operator :=
if (n := len("Hello")) > 3:
print(f"String is long ({n} characters)")
✅ Great for loops and conditionals.
💡 Python 3.8+.
2.🧼 Clean List Comprehension with Conditionals
You can filter and transform in one line.
squares = [x*x for x in range(10) if x % 2 == 0]
➡️ Only keeps even numbers, squares them.
3.🧙♂️ Multiple Assignment (Unpacking)
Python makes this elegant:
a, b, c = [1, 2, 3]
Or even:
first, *middle, last = [10, 20, 30, 40, 50]
Use * to grab “the rest.”
4.🔄 Swap Variables in One Line
Forget temp variables.
a, b = b, a
Clean. Pythonic. Instant swap.
5.🧵 Join Strings Like a Pro
No more manual looping:
words = ["Hello", "World", "2025"]
print(" - ".join(words)) # Hello - World - 2025
Efficient and readable.
6.📚 Use enumerate() Instead of Range + Len
Clean up indexed loops:
names = ["Alice", "Bob", "Charlie"]
for idx, name in enumerate(names):
print(f"{idx}: {name}")
No need for range(len(...))
7.🪄 One-Line If/Else (Ternary)
Use inline for simple conditions:
age = 20
status = "adult" if age >= 18 else "minor"
Perfect for concise assignments.
8.🔁 Loop with an else Block
The else runs if the loop was not broken.
for n in range(5):
if n == 7:
break
else:
print("7 was not found!")
Super underrated.
9.🕳️ Use get() with Dicts to Avoid Key Errors
No more KeyError surprises:
data = {"name": "Nora"}
print(data.get("age", "Not provided"))
Clean fallback values.
10.🕵️♂️ Dictionary Comprehensions
Just like list comprehensions:
squares = {x: x*x for x in range(5)}
Fast and readable dictionary creation.
🎁 Bonus: Zen of Python
Run this in any Python terminal:
import this
You'll get 19 lines of poetic Python wisdom.
💬 Final Thoughts
Python is full of magic 🪄 — the more you explore, the more elegant it gets.
Which trick was your favorite?
Got one that I missed? Drop it in the comments 👇
Let’s keep the Pythonic goodness flowing!
Top comments (1)
Love these Python tricks, especially the walrus operator and unpacking lists. Super handy!