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!