Python Standard Library
The batteries-included modules that mean you rarely need a dependency — collections, itertools, functools, pathlib, and more.
collections
- defaultdict
d = defaultdict(list); d[k].append(x)— no KeyError- Counter
Counter(words).most_common(3)— frequency counting- deque
deque(maxlen=n)— O(1) appends/pops both ends; BFS queues- namedtuple
Point = namedtuple("Point", "x y")— lightweight records
itertools & functools
- Cartesian / combos
product(a, b)·combinations(xs, 2)·permutations(xs)- Chain / group
chain(*lists)·groupby(sorted(xs, key=f), key=f)- Running totals
accumulate(xs)· sliding pairs:pairwise(xs)- Memoize
@lru_cache(maxsize=None)— cache recursive calls- Reduce
reduce(operator.mul, xs, 1)
Files, JSON, time
- pathlib
Path("a/b.txt").read_text()·.glob("*.py")·.exists()- json
json.loads(s)·json.dumps(obj, indent=2)- datetime
datetime.now(timezone.utc).isoformat()- Temp files
tempfile.TemporaryDirectory()— auto-cleaned
Handy tools
- heapq
heappush/heappop— a min-heap;nlargest(k, xs)- bisect
bisect_left(sorted_list, x)— binary search insert point- dataclasses
@dataclass— auto __init__/__repr__/__eq__- enumerate / zip
for i, x in enumerate(xs)·zip(a, b, strict=True)