🔥 Top 50 Python Coding Hacks with Deep Explanations for Beginners (Part 1)
Welcome to Part 1 of our Python Hacks series! In this article, you'll learn 10 smart and powerful Python tricks that make your code cleaner, faster, and more professional. Each hack is explained in simple language with practical examples.
1. Swap Two Variables Instantly
a, b = b, a
Explanation: Normally in other languages, you need a temporary variable to swap values. But in Python, you can swap two variables in one line using tuple unpacking. Internally, Python creates a temporary tuple (b, a) and unpacks it back into a and b.
Example:
a, b = 10, 20
a, b = b, a
print(a, b) # Output: 20 10
2. Reverse a String or List in One Line
text[::-1]
Explanation: The slicing syntax [start:stop:step] allows you to step backwards by using -1. It means “start from the end and move backward”. Works for both strings and lists.
name = "Python"
print(name[::-1]) # Output: nohtyP
3. Find Factorial in One Line
import math; print(math.factorial(5))
Explanation: The math module provides a built-in factorial() function that calculates n! efficiently without loops. This is faster and avoids manual recursion errors.
4. Flatten a Nested List
flat = [x for sub in [[1,2],[3,4]] for x in sub]
Explanation: This is a double list comprehension. The outer loop goes through each sub-list, and the inner loop extracts individual elements. It's a compact way to convert 2D lists into 1D lists.
5. Remove Duplicates While Keeping Order
list(dict.fromkeys([1,2,2,3,1]))
Explanation: When you convert a list to a dictionary using dict.fromkeys(), duplicates are removed automatically because dictionary keys are unique. Then you convert it back to a list to preserve order.
6. Multiple Assignments in One Line
x, y, z = 1, 2, 3
Explanation: Python supports multiple assignments in a single line. It assigns values in the same order from left to right. This is neat and reduces code length.
7. Inline Conditional Expression
status = "Pass" if marks > 40 else "Fail"
Explanation: This is Python’s version of the ternary operator. Instead of writing a full if-else block, you can check a condition in one line. It improves readability for simple logic.
8. Get Unique Words from a Sentence
set(sentence.lower().split())
Explanation: Here we convert the sentence into lowercase to avoid case sensitivity, then split it into words, and finally use a set() to remove duplicates. Useful in NLP or text analysis.
9. Count Frequency of Each Character
from collections import Counter; print(Counter("banana"))
Explanation: Counter creates a dictionary-like object showing how many times each element appears. For example, in "banana", it gives {'b':1, 'a':3, 'n':2}.
10. Check Palindrome Easily
s == s[::-1]
Explanation: A palindrome reads the same backward and forward. Using slicing, we reverse the string and compare it with the original. If both match, it’s a palindrome.
word = "madam"
print(word == word[::-1]) # True
🚀 Coming Next: Part 2 (Data Tricks – Hacks 11–20)
In the next part, we’ll cover powerful data manipulation hacks—sorting, merging, filtering, and more, perfect for real-world Python projects.
💡 Top 50 Python Coding Hacks — Part 2: Data Tricks
Welcome back! In this part, we’ll explore how Python handles data efficiently. These tricks will make your code faster, more readable, and easy to maintain — especially when working with lists and dictionaries.
11. Sort a Dictionary by Its Values
data = {'a': 3, 'b': 1, 'c': 2}
sorted_data = dict(sorted(data.items(), key=lambda x: x[1]))
print(sorted_data)
# Output: {'b': 1, 'c': 2, 'a': 3}
Explanation:
Normally, dictionaries are unordered, but you can sort them by values using sorted().
The key function lambda x: x[1] tells Python to sort based on the dictionary’s value instead of its key. Then we wrap it in dict() to get a proper dictionary again.
12. Merge Two Dictionaries (Python 3.9+)
dict1 = {'x': 10, 'y': 20}
dict2 = {'y': 30, 'z': 40}
merged = dict1 | dict2
print(merged)
# Output: {'x': 10, 'y': 30, 'z': 40}
Explanation:
Python 3.9 introduced the | operator to merge dictionaries easily.
When both have the same key, the right-hand side value (here, dict2) replaces the left one. Before Python 3.9, you had to use {**dict1, **dict2}.
13. Create a Dictionary Using Comprehension
squares = {x: x**2 for x in range(5)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Explanation: Dictionary comprehensions work just like list comprehensions but create key–value pairs. It’s a clean and fast way to build dictionaries programmatically without loops.
14. Convert a List into a Comma-Separated String
fruits = ["apple", "banana", "cherry"]
result = ", ".join(fruits)
print(result)
# Output: apple, banana, cherry
Explanation:
The join() method joins elements of a list into a single string with the chosen separator.
Very useful when printing or writing data to files.
15. Convert a String into a List of Characters
word = "python"
chars = list(word)
print(chars)
# Output: ['p', 'y', 't', 'h', 'o', 'n']
Explanation:
The list() constructor can split any iterable — including strings — into individual characters. Great for analyzing or modifying text.
16. Find the Most Frequent Element in a List
nums = [1, 2, 2, 3, 1, 2, 4]
most_common = max(set(nums), key=nums.count)
print(most_common)
# Output: 2
Explanation:
This hack uses set() to get unique values, then finds the one that appears most often using the count() method.
For large data, use collections.Counter for faster results.
17. Transpose a Matrix in One Line
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(zip(*matrix))
print(transposed)
# Output: [(1, 4), (2, 5), (3, 6)]
Explanation:
The * operator unpacks the matrix rows and passes them into zip().
zip() then groups items by their position — turning rows into columns. This is a popular trick in data manipulation and NumPy-like logic.
18. Find Intersection of Two Lists
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
common = list(set(a) & set(b))
print(common)
# Output: [3, 4]
Explanation:
Using sets makes this operation clean and efficient.
The & operator finds common elements between two sets, similar to SQL “INNER JOIN”.
19. Remove Empty or False Values from a List
data = [0, 1, '', 2, False, 3, None, 'hello']
clean = list(filter(None, data))
print(clean)
# Output: [1, 2, 3, 'hello']
Explanation:
filter(None, data) automatically removes any element that is considered “falsy” in Python — like 0, '', False, or None.
Super handy for cleaning user input or raw datasets.
20. Shuffle a List Randomly
import random
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)
Explanation:
random.shuffle() rearranges list elements randomly, modifying the list in place.
Perfect for quizzes, games, or random sampling applications.
🚀 Coming Next: Part 3 (Built-in Function Hacks — 21–30)
Next, we’ll dive into Python’s most underrated superpower — its built-in functions. You’ll learn how to write cleaner loops, faster calculations, and efficient data handling using one-liners.
⚙️ Top 50 Python Coding Hacks — Part 3: Built-in Function Magic
Python comes with hundreds of built-in functions that make your life easier. In this part, we’ll explore the most useful ones — perfect for writing cleaner, shorter, and smarter programs.
21. Use enumerate() to Get Index with Value
fruits = ["apple", "banana", "cherry"]
for index, value in enumerate(fruits):
print(index, value)
# Output:
# 0 apple
# 1 banana
# 2 cherry
Explanation:
enumerate() automatically adds a counter to your loop. Instead of managing your own index variable, Python does it for you — keeping your loops simple and readable.
22. Combine Multiple Lists Using zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Explanation:
zip() combines two or more lists element-by-element. It’s often used in data processing or when printing table-like results.
23. Test Conditions Using any() and all()
numbers = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in numbers)) # True
print(any(n > 7 for n in numbers)) # True
Explanation:
all() returns True only if *every* condition is True,
while any() returns True if *at least one* condition is True.
These are faster and cleaner than manual for loops for checks.
24. Find the Sum of Elements Instantly
nums = [10, 20, 30]
print(sum(nums)) # Output: 60
Explanation:
Instead of looping manually, use sum() to quickly add up numbers.
It’s optimized in C and works much faster than Python loops.
25. Generate Even Numbers with List Comprehension
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
Explanation:
List comprehensions allow you to build lists in one line.
Here, we loop over a range and filter even numbers using if inside the brackets.
26. Find Duplicate Items in a List
nums = [1, 2, 3, 2, 4, 1, 5]
duplicates = [x for x in set(nums) if nums.count(x) > 1]
print(duplicates)
# Output: [1, 2]
Explanation:
set() removes duplicates temporarily, and we check which elements appeared more than once using count().
It’s quick and easy for small lists.
27. Inline Filtering with List Comprehension
nums = [5, 12, 8, 20, 3]
filtered = [x for x in nums if x > 10]
print(filtered)
# Output: [12, 20]
Explanation:
You can apply conditions directly inside list comprehensions to filter data.
This is cleaner and more “Pythonic” than writing loops and if statements separately.
28. Find Most Common Words in a File
from collections import Counter
words = open("notes.txt").read().split()
print(Counter(words).most_common(5))
Explanation:
The Counter class counts word frequency automatically.
Combine it with .most_common() to get the top N frequent words — useful in text analysis or NLP tasks.
29. Compare Contents of Two Files
same = open("file1.txt").read() == open("file2.txt").read()
print("Files Match!" if same else "Files Differ!")
Explanation: This one-liner compares the full contents of two text files. Simple and effective for checking whether two files are identical — useful in testing or automation scripts.
30. Access Environment Variables Easily
import os
print(os.getenv("PATH"))
Explanation:
The os module allows you to read environment variables like system paths or API keys.
This is essential for writing secure and portable Python applications.
🚀 Coming Next: Part 4 (Data Science & AI Hacks — 31–40)
In the next part, we’ll dive into how Python simplifies Data Science and AI with libraries like Pandas, NumPy, and Statistics — perfect for beginners who want to move into real-world projects.
🔥 Top 50 Python Coding Hacks — Part 4
Is section mein hum focus karenge un tools aur patterns par jo data work aur simple ML tasks ko bahut aasaan banate hain: statistics, pandas, tqdm, JSON/Excel handling, aur chhote performance tricks. Har hack ke baad ek short When to use aur Pitfall/Tip diya gaya hai.
31. Quick Mean and Median with statistics
What & Why
The statistics module provides simple, dependency-free functions for common stats like mean, median and mode — perfect for small scripts and learning before moving to NumPy.
Example
import statistics
data = [10, 20, 30, 40, 50]
print("Mean:", statistics.mean(data))
print("Median:", statistics.median(data))
When to use
Quick checks in scripts, classroom examples, or when you don’t want to install heavy libraries.
Pitfall / Tip
Tip: For large datasets and vectorized operations prefer numpy (faster) and for tables use pandas. statistics.mean works on any iterable of numbers.
32. Load CSV into a DataFrame with pandas.read_csv()
What & Why
pandas is the go-to library for tabular data. read_csv loads CSV to a DataFrame — rows and columns with lots of helper methods for analysis.
Example
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head()) # shows first 5 rows
When to use
Anytime you have CSVs (most common data exchange format). Use DataFrame for cleaning, transforming and visualizing data.
Pitfall / Tip
Tip: If CSV is large, use pd.read_csv("data.csv", chunksize=10000) to stream data in pieces. Also, specify encoding and dtype when needed to avoid surprises.
33. Filter DataFrame Rows with Boolean Indexing
What & Why
Instead of manual loops, Pandas lets you select rows by conditions — very fast and readable.
Example
# select rows where age > 30
filtered = df[df["age"] > 30]
# multiple conditions
subset = df[(df["age"] > 20) & (df["salary"] > 50000)]
When to use
Data cleaning, exploratory analysis, preparing training data for ML.
Pitfall / Tip
Pitfall: Remember to use parentheses around each condition and use bitwise operators (&, |) not and/or. Tip: Use query() for readable complex filters: df.query('age > 20 and salary > 50000').
34. Add or Compute New Column (Vectorized)
What & Why
Operate on entire columns (vectorized ops) instead of row-by-row loops — Pandas and NumPy do the heavy lifting in C for speed.
Example
# create a total column from two columns
df["total"] = df["math"] + df["science"]
# percentage column
df["percent"] = df["total"] / df["max_total"] * 100
When to use
Feature engineering, creating new metrics, or quickly transforming a whole column.
Pitfall / Tip
Tip: Avoid df.apply() for simple arithmetic — vector operations are much faster. If you need row-wise complex logic, consider np.where or apply(axis=1) (but test speed).
35. Quick Plots with Pandas (hist(), plot())
What & Why
Pandas integrates with Matplotlib to make quick exploratory plots. Great for one-line EDA (exploratory data analysis).
Example
# histogram
df["age"].hist()
# scatter plot
df.plot.scatter(x="age", y="salary")
When to use
To visually inspect distributions, outliers and relationships during EDA.
Pitfall / Tip
Tip: For nicer visuals, later move to seaborn or Matplotlib with customized styles. Always check for NaNs — plotting may ignore or cause errors.
36. Check Missing Values Quickly (isnull().sum())
What & Why
A simple one-liner to see how many nulls each column has. First step in data cleaning.
Example
print(df.isnull().sum())
When to use
Always run this after loading data to plan imputation or dropping strategies.
Pitfall / Tip
Pitfall: Some missing values are encoded as strings (e.g., 'NA', '-'), so convert or standardize them first. Tip: Use df.replace(['NA','-'], np.nan, inplace=True) to normalize.
37. Apply a Function to a Column (apply())
What & Why
apply runs a Python function on each element or row. Use it when vectorized ops are not possible.
Example
# simple column transform
df["price_with_tax"] = df["price"].apply(lambda x: round(x * 1.18, 2))
# row-wise operation
df["label"] = df.apply(lambda row: "high" if row["score"] > 80 else "low", axis=1)
When to use
Complex transformations, string parsing, or custom logic per row/element.
Pitfall / Tip
Pitfall: apply is slower than vectorized ops. Tip: Profile your code — if performance matters, try np.where, map or compile functions with numba for speed.
38. Read JSON into DataFrame (pd.read_json / json_normalize)
What & Why
APIs often return JSON. Pandas can read JSON directly, and json_normalize flattens nested JSON to columns.
Example
import pandas as pd, json
# example: line-delimited JSON
df = pd.read_json("data.json", lines=True)
# nested JSON
from pandas import json_normalize
data = json.load(open("nested.json"))
flat = json_normalize(data, record_path=["items"], meta=["id", "date"])
When to use
When working with API responses or nested data needing tabular form for analysis or training models.
Pitfall / Tip
Tip: Inspect JSON structure first. For deeply nested JSON, build a custom normalizing function or use iterative flattening to control column names.
39. Export DataFrame to Excel or CSV
What & Why
Shareable outputs: Excel for business users, CSV for pipelines and systems. Pandas makes it easy.
Example
# CSV
df.to_csv("out.csv", index=False)
# Excel
df.to_excel("report.xlsx", sheet_name="Sheet1", index=False)
When to use
Reporting, data handoff to non-technical stakeholders, or saving processed datasets.
Pitfall / Tip
Pitfall: Excel files can be large and slow. Tip: For many rows, prefer compressed CSV (compression='gzip') or Parquet (df.to_parquet()) for speed and size efficiency.
40. Show Progress with tqdm
What & Why
tqdm adds progress bars to loops with almost no changes to code — great UX when processing large data or training models.
Example
from tqdm import tqdm
for i in tqdm(range(100000)):
# long running processing
pass
# with pandas
from tqdm import tqdm
tqdm.pandas()
df["new"] = df["text"].progress_apply(process_function)
When to use
Whenever loops or transformations take noticeable time — shows you how far along the job is and ETA.
Pitfall / Tip
Tip: Use tqdm(total=...) for custom iterables and be careful with nested progress bars (use tqdm(total=...) and leave=False for neat output).
df.isnull().sum(), create a new column with a vectorized op, and show a histogram. This single loop-through will cement many of the above hacks.Next up: Part 5 (Hacks 41–50) — Web, Automation & Advanced professional tips (Selenium, requests, lru_cache, __slots__, decorator timing and more). Want me to generate Part 5 now?
🔥 Top 50 Python Coding Hacks — Part 5
Welcome to the final part of our Top 50 Python Coding Hacks series. In this section, you’ll explore web automation, API requests, caching, decorators, and optimization tricks that real-world Python developers use daily. Each hack includes a plain-language explanation and working example.
41. Simple API Calls with requests
What & Why
The requests library is your gateway to the web. It helps you send HTTP requests to APIs and websites effortlessly.
Example
import requests
url = "https://api.github.com/users/octocat"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("Name:", data["name"])
else:
print("Request failed!")
When to use
Fetching weather data, currency rates, GitHub repos, or connecting with any REST API.
Tip
Use timeout to prevent your program from hanging:
requests.get(url, timeout=5)
42. Automate Browser Tasks using selenium
What & Why
selenium allows Python to control a web browser — ideal for testing, form filling, or scraping data where APIs aren’t available.
Example
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.google.com")
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Python automation")
search_box.submit()
print(driver.title)
driver.quit()
When to use
For websites that require interaction (login, buttons, or dynamic content).
Pitfall / Tip
Tip: Always use WebDriverWait for elements to load. Don’t scrape sites that disallow automation (check robots.txt).
43. Use lru_cache to Speed Up Repeated Calls
What & Why
The @lru_cache decorator from functools saves results of expensive function calls. If the same input repeats, it returns instantly.
Example
from functools import lru_cache
import time
@lru_cache(maxsize=None)
def slow_function(n):
time.sleep(2)
return n * n
print(slow_function(5)) # takes 2 seconds
print(slow_function(5)) # instant!
When to use
For recursive algorithms (like Fibonacci) or repeated computations with same parameters.
Tip
Use slow_function.cache_clear() to clear cache when data changes.
44. Track Function Performance with a Decorator
What & Why
Decorators can wrap a function to measure how long it takes to run — useful for profiling code performance.
Example
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.3f} sec")
return result
return wrapper
@timer
def slow_task():
time.sleep(1)
slow_task()
When to use
When optimizing loops, functions, or algorithms for performance.
Tip
Combine with @lru_cache to both measure and speed up heavy functions.
45. Send Email via Python (Automation Hack)
What & Why
Automating email reports or alerts using the built-in smtplib.
Example
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("This is a test email from Python!")
msg["Subject"] = "Python Automation"
msg["From"] = "you@gmail.com"
msg["To"] = "friend@gmail.com"
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login("you@gmail.com", "your_app_password")
server.send_message(msg)
When to use
For automated notifications, reports, or reminders from scripts.
Pitfall
Don’t use your real password — generate an App Password for Gmail or Outlook.
46. Run System Commands with subprocess
What & Why
Need to automate terminal commands or scripts? subprocess lets Python control the system shell safely.
Example
import subprocess
result = subprocess.run(["echo", "Hello World!"], capture_output=True, text=True)
print(result.stdout)
When to use
In DevOps scripts, deployment tools, or server maintenance automation.
Tip
Prefer list format (not shell=True) to avoid injection risks.
47. Simple File Automation with os and shutil
What & Why
Python can rename, move, and delete files easily — no need for manual file management.
Example
import os, shutil
os.rename("old.txt", "new.txt")
shutil.copy("new.txt", "backup.txt")
os.remove("backup.txt")
When to use
Batch renaming, folder cleanup, or data backup automation.
Tip
Wrap file operations in try/except blocks to avoid accidental deletions.
48. Create Virtual Environments the Easy Way
What & Why
Virtual environments keep your project’s dependencies isolated — every professional Python project uses them.
Example
python -m venv myenv
source myenv/bin/activate # on mac/linux
myenv\Scripts\activate # on windows
pip install requests pandas
When to use
Every time you start a new project or work on client code.
Tip
Deactivate using deactivate. For advanced users, try poetry or pipenv.
49. Speed Up Code with multiprocessing
What & Why
Python’s Global Interpreter Lock (GIL) stops threads from running in true parallel. Use multiprocessing to bypass that and use all CPU cores.
Example
from multiprocessing import Pool
def square(n):
return n * n
with Pool() as pool:
results = pool.map(square, [1, 2, 3, 4, 5])
print(results)
When to use
Large numeric computations, image processing, or file analysis tasks.
Tip
Don’t use multiprocessing for simple I/O — it adds overhead. Use async for that.
50. Create REST APIs using FastAPI
What & Why
FastAPI is a modern Python framework for building APIs quickly — fast, asynchronous, and great for AI or web apps.
Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get("/")
def home():
return {"message": "Hello from FastAPI"}
@app.post("/item/")
def create_item(item: Item):
return {"item_name": item.name, "price": item.price}
When to use
Building APIs for your mobile apps, dashboards, or ML model deployment.
Tip
Run with uvicorn main:app --reload. Explore Swagger UI at http://127.0.0.1:8000/docs.
- Use
requeststo fetch data - Process it in
pandas - Automate reporting via
email - Deploy with
FastAPI

.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)