Python – Code Snippets

August 19, 20264 min readUpdated 8/20/2026

The short answers you keep looking up. Every block here runs on Python 3.12 as written — copy, paste, move on.

Files

from pathlib import Path

Path("notes.txt").write_text("alpha\nbeta\ngamma\n", encoding="utf-8")

# Read a whole file
text = Path("notes.txt").read_text(encoding="utf-8")
print(len(text))                                   # Output: 17

# Read into a list of lines, without the newlines
lines = Path("notes.txt").read_text(encoding="utf-8").splitlines()
print(lines)                                       # Output: ['alpha', 'beta', 'gamma']

# Append one line
with open("notes.txt", "a", encoding="utf-8") as handle:
    handle.write("delta\n")

print(Path("notes.txt").read_text(encoding="utf-8").splitlines()[-1])   # Output: delta

# Every .txt in a directory tree
print(sorted(p.name for p in Path(".").rglob("*.txt")))     # Output: ['notes.txt']

Dicts

balances = {"Checking": 1250.0, "Savings": 8400.5, "Credit": -320.75}

# Sort by value
print(sorted(balances.items(), key=lambda kv: kv[1])[0])   # Output: ('Credit', -320.75)

# Sort by value, descending, as a dict
print(dict(sorted(balances.items(), key=lambda kv: -kv[1])))
# Output: {'Savings': 8400.5, 'Checking': 1250.0, 'Credit': -320.75}

# The key with the largest value
print(max(balances, key=balances.get))     # Output: Savings

# Invert it
print({v: k for k, v in balances.items()}[1250.0])     # Output: Checking

# Merge, right wins
print({"a": 1, "b": 2} | {"b": 99})        # Output: {'a': 1, 'b': 99}

# Filter
print({k: v for k, v in balances.items() if v > 0})
# Output: {'Checking': 1250.0, 'Savings': 8400.5}

Lists

from collections import Counter

# Flatten one level
rows = [[1, 2], [3, 4], [5]]
print([x for row in rows for x in row])          # Output: [1, 2, 3, 4, 5]

# Remove duplicates, keeping order
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items)))                # Output: ['b', 'a', 'c']

# Count occurrences
print(Counter(items).most_common(1))             # Output: [('b', 2)]

# Chunk into groups of n
def chunks(seq, n):
    return [seq[i:i + n] for i in range(0, len(seq), n)]

print(chunks([1, 2, 3, 4, 5], 2))                # Output: [[1, 2], [3, 4], [5]]

# Index and item together
print(list(enumerate(["a", "b"], start=1)))      # Output: [(1, 'a'), (2, 'b')]

# Two lists into pairs
print(list(zip(["a", "b"], [1, 2])))             # Output: [('a', 1), ('b', 2)]

Strings

line = "  1,alice@bank.test,Alice Cooper  "

# Split into fields
print(line.strip().split(","))
# Output: ['1', 'alice@bank.test', 'Alice Cooper']

# Join with a separator (numbers need converting)
print(", ".join(str(n) for n in [1, 2, 3]))      # Output: 1, 2, 3

# Strip a known prefix or suffix — NOT strip(), which removes characters
print("report.csv".removesuffix(".csv"))         # Output: report

# Pad and align for a table
print(f"{'Deposit':<12}{100.5:>10,.2f}")         # Output: Deposit         100.50

# Truncate with an ellipsis
text = "a rather long description here"
print(text[:17] + "…" if len(text) > 18 else text)   # Output: a rather long des…

# Mask all but the last four
print("*" * 12 + "4321"[-4:])                    # Output: ************4321

Numbers and money

from decimal import Decimal, ROUND_HALF_UP

# Money: Decimal from a STRING, never a float
total = Decimal("0.1") + Decimal("0.2")
print(total)                                     # Output: 0.3

# Round to cents, the way people expect
print(Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))   # Output: 2.35

# Format for display
print(f"${9650.5:,.2f}")                         # Output: $9,650.50
print(f"{0.0725:.1%}")                           # Output: 7.2%

# Clamp to a range
print(max(0, min(100, 150)))                     # Output: 100

# Safe division
def divide(a, b):
    return a / b if b else 0

print(divide(10, 0))                             # Output: 0

Dates

from datetime import datetime, timedelta, timezone

when = datetime(2026, 8, 20, 13, 45, tzinfo=timezone.utc)

print(when.strftime("%Y-%m-%d %H:%M"))     # Output: 2026-08-20 13:45
print(when.isoformat())                    # Output: 2026-08-20T13:45:00+00:00
print((when + timedelta(days=7)).date())   # Output: 2026-08-27

# Parse a string
print(datetime.strptime("2026-08-20", "%Y-%m-%d").date())   # Output: 2026-08-20

# Round-trip an ISO string
print(datetime.fromisoformat("2026-08-20T13:45:00+00:00") == when)   # Output: True

Use datetime.now(timezone.utc) rather than datetime.now() for anything stored or compared — a naive datetime has no timezone and cannot be compared with an aware one.

JSON

import json
from pathlib import Path

settings = {"currency": "USD", "features": ["transfer", "statements"]}

# Object to file, readable
Path("settings.json").write_text(json.dumps(settings, indent=2), encoding="utf-8")

# File to object
loaded = json.loads(Path("settings.json").read_text(encoding="utf-8"))
print(loaded["features"][0])           # Output: transfer

# Sorted keys, for a stable diff
print(json.dumps({"b": 1, "a": 2}, sort_keys=True))   # Output: {"a": 2, "b": 1}

Sets and comparisons

before = {"a@x.com", "b@x.com", "c@x.com"}
after = {"b@x.com", "c@x.com", "d@x.com"}

print(sorted(before & after))        # Output: ['b@x.com', 'c@x.com']
print(sorted(before - after))        # Output: ['a@x.com']
print(sorted(after - before))        # Output: ['d@x.com']
print(sorted(before ^ after))        # Output: ['a@x.com', 'd@x.com']

# Any overlap at all?
print(bool(before & after))          # Output: True

# De-duplicate two lists into one
print(sorted(set(["a", "b"]) | set(["b", "c"])))     # Output: ['a', 'b', 'c']

Intersection, difference and symmetric difference answer "what is in both", "what was removed" and "what changed" — which is most of what a diff between two datasets needs.

Environment and arguments

import os
import sys

# An environment variable with a default — never crash on a missing one
print(os.environ.get("BANK_DATA_DIR", "./data"))     # Output: ./data

# A required one, failing loudly and early
def required(name):
    value = os.environ.get(name)
    if not value:
        raise SystemExit(f"{name} is not set")
    return value

print(callable(required))                            # Output: True

# Which Python is running this
print(sys.version_info >= (3, 12))                   # Output: True

os.environ.get(name, default) for anything optional. For a required setting, fail at startup with a message naming the variable — a KeyError three functions deep, an hour into a job, is the alternative.

Timing and retrying

import time

# Time a block
started = time.perf_counter()
sum(range(100000))
print(round(time.perf_counter() - started, 1) < 1.0)     # Output: True

# Retry with backoff
def retry(fn, attempts=3, delay=0.01):
    for attempt in range(1, attempts + 1):
        try:
            return fn()
        except Exception:
            if attempt == attempts:
                raise
            time.sleep(delay * attempt)

calls = []
def flaky():
    calls.append(1)
    if len(calls) < 3:
        raise ConnectionError("not yet")
    return "ok"

print(retry(flaky))       # Output: ok
print(len(calls))         # Output: 3

perf_counter rather than time() — it is monotonic, so a clock adjustment cannot produce a negative duration. The retry re-raises on the final attempt rather than returning None, which is the detail most hand-written retries get wrong.

That is the end of the track. Back to Get Started for the full contents.