DEV Community

Art Baker
Art Baker

Posted on

The Python Quick Reference I Actually Use (Cheat Sheet)

I keep a single-page Python reference that covers 90% of what I type daily. Here are the highlights.


Data Structures — the 10 patterns that matter

# List comprehension with filter
[x**2 for x in nums if x > 1]

# Dict comprehension
{k: v for k, v in d.items() if v > 0}

# Set operations
a & b   # intersection
a | b   # union
a - b   # difference

# Unpacking
a, *rest = [1, 2, 3, 4]  # a=1, rest=[2,3,4]
merged = {**d1, **d2}     # merge dicts (3.9+: d1 | d2)
Enter fullscreen mode Exit fullscreen mode

Strings

f"Name: {name!r}"               # f-string with repr
" ".join(["a", "b", "c"])       # "a b c"
text.split()                     # split on whitespace
re.sub(r"\s+", " ", text)       # collapse whitespace
Enter fullscreen mode Exit fullscreen mode

Files — pathlib over os.path

from pathlib import Path

text = Path("file.txt").read_text()
Path("out.txt").write_text("hello")

for f in Path(".").glob("**/*.py"):
    print(f.name)
Enter fullscreen mode Exit fullscreen mode

Functions

# Decorator
from functools import wraps
def timer(fn):
    @wraps(fn)
    def wrapper(*a, **kw):
        t0 = time.time()
        r = fn(*a, **kw)
        print(f"{fn.__name__}: {time.time()-t0:.2f}s")
        return r
    return wrapper

# Generator
def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i+n]
Enter fullscreen mode Exit fullscreen mode

One-Liners I Use Weekly

# Flatten nested list
flat = [x for sub in nested for x in sub]

# Remove duplicates preserving order
seen = set()
unique = [x for x in items if x not in seen and not seen.add(x)]

# Invert a dict
inv = {v: k for k, v in d.items()}

# Counter
from collections import Counter
Counter(words).most_common(5)
Enter fullscreen mode Exit fullscreen mode

Async (httpx pattern)

import asyncio, httpx

async def fetch_all(urls):
    async with httpx.AsyncClient() as c:
        return await asyncio.gather(*(c.get(u) for u in urls))

results = asyncio.run(fetch_all(["https://a.com", "https://b.com"]))
Enter fullscreen mode Exit fullscreen mode

Full cheat sheet

This is ~30% of my full reference. The complete version covers: data structures, strings, files, JSON/CSV, functions, decorators, generators, classes, dataclasses, error handling, async, match statements, context managers, and every import I reach for.

PDF: payhip.com/b/1xsQH ($5)

Also:

Top comments (0)