Skip to content

Python Code Snippets: Reusable Examples for Common Tasks

Short, focused Python snippets for tasks that come up repeatedly. Each is a complete, runnable example. Run with python -c "..." or save to a .py file.

# Loop through a list
items = ["api", "worker", "scheduler"]
for item in items:
print(item)
# Loop with index
for i, item in enumerate(items):
print(i, item)
# List comprehension
upper = [item.upper() for item in items]
filtered = [item for item in items if len(item) > 4]
# Dict comprehension
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}
expensive = {k: v for k, v in prices.items() if v > 1.0}
# Count frequencies
from collections import Counter
values = ["python", "python", "api", "docs"]
counts = Counter(values)
print(counts.most_common(2)) # [('python', 2), ('api', 1)]
# Merge dicts (Python 3.9+)
defaults = {"timeout": 30, "retries": 3}
overrides = {"retries": 5}
config = defaults | overrides # {'timeout': 30, 'retries': 5}
# f-string with format spec
amount = 149.99
print(f"Total: ${amount:.2f}") # Total: $149.99
print(f"{'ORD-001':<20} {amount:>10.2f}") # alignment
# Multiline string
message = (
"Dear customer,\n"
"Your order has shipped.\n"
"Expected delivery: 3-5 days."
)
# Split and join
csv_line = "ORD-001,BensonCo,149.99"
parts = csv_line.split(",") # ['ORD-001', 'BensonCo', '149.99']
rejoined = "|".join(parts) # 'ORD-001|BensonCo|149.99'
# Strip whitespace and check prefix/suffix
raw = " ORD-001 "
clean = raw.strip()
print(clean.startswith("ORD")) # True
print(clean.endswith("001")) # True
from pathlib import Path
import json
# Write a text file
Path("report.txt").write_text("Order Report\n", encoding="utf-8")
# Read a text file
content = Path("report.txt").read_text(encoding="utf-8")
# Append to a file
with Path("report.txt").open("a", encoding="utf-8") as f:
f.write("ORD-001: confirmed\n")
# Write JSON
data = {"order_id": "ORD-001", "amount": 149.99}
Path("order.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
# Read JSON
loaded = json.loads(Path("order.json").read_text(encoding="utf-8"))
print(loaded["amount"]) # 149.99
# List files in a directory
for csv_file in Path(".").glob("*.csv"):
print(csv_file.name)
# Create directories recursively
Path("data/exports/2026").mkdir(parents=True, exist_ok=True)
# Basic try/except
try:
value = int("42")
except ValueError:
value = 0
# Multiple exception types
try:
result = risky_operation()
except (ValueError, TypeError) as e:
print(f"Input error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
raise # re-raise to preserve traceback
# Custom exception
class OrderNotFoundError(Exception):
def __init__(self, order_id: str) -> None:
super().__init__(f"Order {order_id!r} not found")
self.order_id = order_id
# Raise with chained cause
try:
connect_to_db()
except ConnectionError as e:
raise RuntimeError("Cannot fetch order") from e
import os
from dotenv import load_dotenv # pip install python-dotenv
load_dotenv() # loads .env file if present
# Get a required variable (raises KeyError if missing)
db_url = os.environ["DATABASE_URL"]
# Get with a default
debug = os.environ.get("DEBUG", "false").lower() == "true"
# Check all required variables are set
required = ["DATABASE_URL", "OPENAI_API_KEY", "SECRET_KEY"]
missing = [k for k in required if not os.environ.get(k)]
if missing:
raise RuntimeError(f"Missing environment variables: {missing}")
import requests # pip install requests
# GET
response = requests.get(
"https://api.example.test/orders",
params={"status": "pending"},
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
response.raise_for_status() # raises HTTPError on 4xx/5xx
orders = response.json()
# POST
response = requests.post(
"https://api.example.test/orders",
json={"customer": "BensonCo", "amount": 149.99},
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
response.raise_for_status()
created = response.json()
print(created["order_id"])
from datetime import date, datetime, timedelta, timezone
today = date.today()
now = datetime.now(tz=timezone.utc)
# Arithmetic
seven_days = today + timedelta(days=7)
diff = datetime(2026, 12, 31) - datetime(2026, 11, 13)
print(diff.days) # 48
# Format and parse
print(now.strftime("%Y-%m-%d %H:%M:%S"))
parsed = datetime.strptime("2026-11-13 09:00", "%Y-%m-%d %H:%M")
iso = datetime.fromisoformat("2026-11-13T09:00:00+00:00")
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: str
customer: str
amount: float
tags: list[str] = field(default_factory=list)
def total(self, tax_rate: float = 0.08) -> float:
return round(self.amount * (1 + tax_rate), 2)
o = Order("ORD-001", "BensonCo", 100.0, ["priority"])
print(o) # Order(order_id='ORD-001', customer='BensonCo', amount=100.0, tags=['priority'])
print(o.total()) # 108.0
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s — %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Order %s confirmed", "ORD-001")
logger.warning("Retry %d for order %s", 2, "ORD-002")
logger.error("Payment failed: %s", "card declined")