Python Cheatsheet

Modern Python 3.12+ essentials. Covers syntax, collections, comprehensions, and common stdlib.

1 credit

Basics

5 items
f-string
f"Hello, {name}! {x:.2f}"
Walrus
if (n := len(data)) > 10: ...
Ternary
x = a if cond else b
Truthy check
if not items: (empty list / "" / 0 / None all falsy)
Unpack
a, *rest = [1,2,3,4] → a=1, rest=[2,3,4]

Collections

6 items
List comp
[x*2 for x in nums if x > 0]
Dict comp
{k: v for k, v in items}
Set
{1, 2, 3} / set(list)
Zip
for a, b in zip(xs, ys): ...
Enumerate
for i, x in enumerate(xs, start=1): ...
Merge dicts
{**a, **b} or a | b (3.9+)

Functions & types

python
from dataclasses import dataclass
from typing import Iterable

@dataclass
class User:
    id: int
    name: str
    active: bool = True

def sum_active(users: Iterable[User]) -> int:
    return sum(1 for u in users if u.active)

Stdlib quick wins

6 items
pathlib
from pathlib import Path; Path("x").read_text()
json
import json; json.loads(s); json.dumps(obj, indent=2)
itertools
chain, groupby, product, combinations, islice
functools
lru_cache, reduce, partial, cached_property
collections
Counter, defaultdict, deque, OrderedDict
subprocess
run(["ls"], capture_output=True, text=True, check=True)

Further reading