Python Secrets Unlocked
π Python Secrets Unlocked: Hidden Tricks & Hacks Every Developer MUST Know πβ¨
Python is simpleβ¦ but mastering it? Thatβs where the magic happens. π‘ In this blog, youβll discover hidden Python tricks, pro-level hacks, and best practices that can make your code faster, cleaner, and more powerful. πͺ
π₯ 1. Swap Variables Without a Temp Variable
β Traditional Way:
a = 5
b = 10
temp = a
a = b
b = temp
β Pythonic Way:
a, b = b, a
π‘ Python uses tuple unpacking internally β cleaner & faster.
β‘ 2. List Comprehensions (Write Less, Do More)
β Normal Loop:
squares = []
for i in range(10):
squares.append(i*i)
β Pythonic Way:
squares = [i*i for i in range(10)]
π₯ Cleaner, faster, and readable!
π§ 3. Use enumerate() Instead of Manual Indexing
β Bad Practice:
index = 0
for value in data:
print(index, value)
index += 1
β Better:
for index, value in enumerate(data):
print(index, value)
π‘ Cleaner + avoids bugs.
π― 4. Multiple Assignments in One Line
a, b, c = 1, 2, 3
Or even:
a = b = c = 10
β‘ Saves time and improves readability.
π§ͺ 5. Use zip() to Iterate Multiple Lists
names = ["Lakhveer", "Rahul"]
scores = [90, 85]
for name, score in zip(names, scores):
print(name, score)
π‘ Perfect for parallel iteration.
π 6. Check Memory Usage with sys.getsizeof()
import sys
print(sys.getsizeof([1,2,3]))
π Helps optimize memory-heavy applications.
π§° 7. Use set for Faster Lookups
numbers = [1,2,3,4,5]
if 3 in numbers: # slower
Better:
numbers = {1,2,3,4,5}
if 3 in numbers: # faster β‘
π‘ Sets use hashing β O(1) lookup time
π² 8. Random Sampling Trick
import random
nums = [1,2,3,4,5]
print(random.sample(nums, 2))
π₯ Get random elements without repetition.
π¦ 9. Use defaultdict to Avoid Key Errors
from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d) # {'a': 1}
π‘ No need to check if key exists!
π 10. Flatten a List Using One Line
matrix = [[1,2], [3,4], [5,6]]
flat = [item for sublist in matrix for item in sublist]
π₯ Very useful in data processing.
π§© 11. Lambda Functions for Quick Operations
add = lambda x, y: x + y
print(add(2,3))
β‘ Use for short, one-time functions
π οΈ 12. Use *args and **kwargs for Flexibility
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1,2,3, name="Lakhveer")
π‘ Helps build dynamic & reusable functions
β±οΈ 13. Measure Execution Time Quickly
import time
start = time.time()
# your code
end = time.time()
print(end - start)
π₯ Useful for performance optimization.
π― 14. Use any() and all()
nums = [True, True, False]
print(any(nums)) # True
print(all(nums)) # False
π‘ Clean boolean checks in one line.
𧬠15. String Reverse Trick
text = "Python"
print(text[::-1])
β‘ Super fast slicing trick!
π Must-Do Things as a Pro Developer πΌ
β 1. Write Pythonic Code
- Prefer readability over cleverness
- Follow PEP 8 guidelines
β 2. Use Virtual Environments
python -m venv env
source env/bin/activate
π‘ Avoid dependency conflicts
β 3. Write Tests π§ͺ
- Use
pytestorunittest - Prevent bugs early
β 4. Use Logging Instead of Print
import logging
logging.info("This is info")
π‘ Production-ready debugging
β 5. Optimize Only When Needed
- First β correct code
- Then β optimize π₯
π« Common Mistakes to Avoid β
β 1. Using Mutable Default Arguments
def func(a=[]): # BAD
β Fix:
def func(a=None):
if a is None:
a = []
β 2. Overusing Global Variables
π₯ Makes code messy and hard to debug
β 3. Ignoring Exceptions
try:
risky_code()
except:
pass # BAD β
π‘ Always handle errors properly!
β 4. Writing Long Functions
π₯ Hard to maintain
β Break into smaller functions
β 5. Not Using Built-in Functions
π‘ Python has powerful built-ins:
map()filter()sorted()
Use them!
π― Final Thoughts π‘
Python is not just about writing codeβ¦ Itβs about writing elegant, efficient, and scalable code π
π Master these hidden tricks, and youβll:
- Write cleaner code β¨
- Debug faster β‘
- Think like a pro developer π§
π¬ Pro Tip:
βCode is like poetry β the shorter and clearer, the better.β βοΈ
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.