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.
Collections
Section titled “Collections”# Loop through a listitems = ["api", "worker", "scheduler"]for item in items: print(item)
# Loop with indexfor i, item in enumerate(items): print(i, item)
# List comprehensionupper = [item.upper() for item in items]filtered = [item for item in items if len(item) > 4]
# Dict comprehensionprices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}expensive = {k: v for k, v in prices.items() if v > 1.0}
# Count frequenciesfrom collections import Countervalues = ["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}Strings
Section titled “Strings”# f-string with format specamount = 149.99print(f"Total: ${amount:.2f}") # Total: $149.99print(f"{'ORD-001':<20} {amount:>10.2f}") # alignment
# Multiline stringmessage = ( "Dear customer,\n" "Your order has shipped.\n" "Expected delivery: 3-5 days.")
# Split and joincsv_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/suffixraw = " ORD-001 "clean = raw.strip()print(clean.startswith("ORD")) # Trueprint(clean.endswith("001")) # TrueFiles and paths
Section titled “Files and paths”from pathlib import Pathimport json
# Write a text filePath("report.txt").write_text("Order Report\n", encoding="utf-8")
# Read a text filecontent = Path("report.txt").read_text(encoding="utf-8")
# Append to a filewith Path("report.txt").open("a", encoding="utf-8") as f: f.write("ORD-001: confirmed\n")
# Write JSONdata = {"order_id": "ORD-001", "amount": 149.99}Path("order.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
# Read JSONloaded = json.loads(Path("order.json").read_text(encoding="utf-8"))print(loaded["amount"]) # 149.99
# List files in a directoryfor csv_file in Path(".").glob("*.csv"): print(csv_file.name)
# Create directories recursivelyPath("data/exports/2026").mkdir(parents=True, exist_ok=True)Exception handling
Section titled “Exception handling”# Basic try/excepttry: value = int("42")except ValueError: value = 0
# Multiple exception typestry: 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 exceptionclass 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 causetry: connect_to_db()except ConnectionError as e: raise RuntimeError("Cannot fetch order") from eEnvironment variables
Section titled “Environment variables”import osfrom 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 defaultdebug = os.environ.get("DEBUG", "false").lower() == "true"
# Check all required variables are setrequired = ["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}")HTTP requests
Section titled “HTTP requests”import requests # pip install requests
# GETresponse = 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/5xxorders = response.json()
# POSTresponse = 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"])Dates and times
Section titled “Dates and times”from datetime import date, datetime, timedelta, timezone
today = date.today()now = datetime.now(tz=timezone.utc)
# Arithmeticseven_days = today + timedelta(days=7)diff = datetime(2026, 12, 31) - datetime(2026, 11, 13)print(diff.days) # 48
# Format and parseprint(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")Dataclasses
Section titled “Dataclasses”from dataclasses import dataclass, field
@dataclassclass 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.0Logging
Section titled “Logging”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")Related pages
Section titled “Related pages”- Python basics — syntax quick reference
- Python standard library — module overview
- Python error handling — exceptions in depth
- Python file I/O — files in depth