1.collections
collections supplies specialized containers — Counter, defaultdict, namedtuple, deque — that replace common hand-written patterns built from plain dicts and lists.
Key features
- Counter(iterable) tallies items; .most_common(n) returns the top n as (item, count) pairs
- defaultdict(factory) calls factory() to create a value the first time a key is missing
- namedtuple builds a tuple subclass with named, dot-accessible fields — still immutable
- deque supports O(1) append/pop from both ends; a list is O(n) at the front
- ChainMap searches several dicts in order without copying or merging them
collections — the containers worth knowing
- Counting items — Counter
- Grouping into a dict — defaultdict(list)
- Named fields — namedtuple
- Fast both ends — deque
Command
from collections import Counter, defaultdict, namedtuple, deque
Counter(iterable)
defaultdict(factory)
namedtuple("Name", ["field1", "field2"])
deque(iterable, maxlen=None)Counter tallies, defaultdict auto-creates missing values, namedtuple names fields, deque is fast at both ends — pick the one matching the shape of the problem.