collections
Six ready-made containers that replace the loops everyone writes by hand: counting (Counter), grouping (defaultdict), queues and sliding windows (deque), records (namedtuple), ordered-dict tricks (OrderedDict) and layered lookups (ChainMap).
from collections import Counter, deque, defaultdict import collections
Demo
from collections import Counter Counter('the cat and the hat and the bat'.split()).most_common(2)
most_common orders by count and keeps the first-seen order among equal counts, so in "ties" b beats a only because it appeared first. The deque drops items from the left once maxlen is reached, and a negative maxlen is a ValueError. In the grouping tab an empty word has no first letter: word[0] raises IndexError before defaultdict is even asked.
Members
Common patterns
from collections import Counter counts = Counter(words) counts.most_common(10)
from collections import defaultdict by_city = defaultdict(list) for row in rows: by_city[row["city"]].append(row)
from collections import deque queue = deque() queue.append(job) next_job = queue.popleft()
from collections import deque recent = deque(maxlen=100) for event in events: recent.append(event)
from collections import namedtuple Point = namedtuple('Point', 'x y') p = Point(3, 4) p.x + p.y
Examples
Pitfalls
import collections collections.Mapping
import collections.abc isinstance({}, collections.abc.Mapping)
from collections import defaultdict d = defaultdict(list) if d['ghost']: pass d
from collections import defaultdict d = defaultdict(list) if 'ghost' in d: pass d
queue = [1, 2, 3] queue.pop(0)
from collections import deque queue = deque([1, 2, 3]) queue.popleft()
When to use
- Counting and ranking things → Counter
- Building dicts of lists or sets → defaultdict
- Queues, stacks and "last N" buffers → deque
- Small immutable records → namedtuple
- Layered configuration or scopes → ChainMap
- Records that need defaults, type hints and methods → dataclasses (or typing.NamedTuple)
- Random access into the middle of a long sequence → list (deque indexing is O(n) in the middle)
- Priority queues → heapq; thread-to-thread queues → queue.Queue
Notes
FAQ
A standard-library module of specialized container types: Counter (counting), deque (fast double-ended queue), defaultdict (dict with automatic default values), OrderedDict (dict with reordering methods), namedtuple (tuples with named fields), ChainMap (several dicts searched as one) and UserDict/UserList/UserString (base classes for custom containers).