collections: Counter, defaultdict, deque, ChainMap
Four stdlib types that replace a surprising amount of hand-rolled boilerplate: Counter for frequency
counting, defaultdict for "group into a dict without checking if the key exists yet," deque for a
double-ended queue with O(1) operations at both ends (vs. a list's O(n) insert(0, ...)), and
ChainMap for layering multiple dicts into one logical view without copying them.
from collections import Counter, defaultdict, deque, ChainMap
words = "the quick brown fox jumps over the lazy dog the fox runs".split()
c = Counter(words)
print("Counter:", c)
print("most_common(2):", c.most_common(2))
dd = defaultdict(list)
for word in words:
dd[len(word)].append(word)
print("defaultdict grouped by length:", dict(dd))
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print("deque after appendleft/append:", d)
cm = ChainMap({"a": 1}, {"b": 2, "a": 99})
print("ChainMap lookup (first dict wins):", cm["a"], cm["b"])
The O(1) vs O(n) claim only shows up at real scale -- on a large structure, deque wins by three orders of magnitude:
import timeit
setup_list = "lst = list(range(200000))"
setup_deque = "from collections import deque; d = deque(range(200000))"
t_list = timeit.timeit("lst.insert(0, -1); lst.pop(0)", setup=setup_list, number=2000)
t_deque = timeit.timeit("d.appendleft(-1); d.popleft()", setup=setup_deque, number=2000)
print(f"200,000-element structure, 2000 operations each:")
print(f" list.insert(0,...) + pop(0): {t_list:.4f}s")
print(f" deque.appendleft + popleft: {t_deque:.4f}s")
print(f" list is ~{t_list/t_deque:.0f}x slower -- insert(0) must shift every remaining element")