Python collections Module
In this page:
from collections import Counter, defaultdict, deque, namedtuple
counter = Counter(iterable)
groups = defaultdict(list)
queue = deque(iterable)
Counting Items with Counter
Counter is a dict subclass built specifically for tallying: passing it any iterable automatically counts how many times each element appears, turning a manual loop-and-increment pattern into a single constructor call.
It also supports arithmetic between counters and a most_common() method for ranked frequency results.
Example: Counting Items with Counter
from collections import Counter
counts = Counter(["a", "b", "a", "c", "a"]) # tallies how many times each item appears
print(counts)
print(counts.most_common(1)) # the single most frequent item
Grouping with defaultdict
defaultdict is a dict subclass that supplies an automatic default value (via a factory you provide, like list or int) whenever a missing key is accessed, instead of raising KeyError.
This removes the need to check if key not in dict before appending to a per-key list or incrementing a per-key counter.
Example: Grouping with defaultdict
from collections import defaultdict
groups = defaultdict(list) # missing keys default to a new empty list
groups["fruits"].append("apple") # no need to check if "fruits" exists first
print(groups)
Named Tuples with namedtuple
namedtuple generates a lightweight, immutable tuple subclass whose fields have names as well as positions, so you can write point.x instead of the less readable point[0].
It's a good middle ground between a plain tuple (no names) and a full class (more machinery than you need for a simple record).
Example: Named Tuples with namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"]) # tuple subclass with named fields
p = Point(1, 2)
print(p.x, p.y) # access by name instead of index
Double-Ended Queue with deque
deque supports O(1) appends and pops from both ends, unlike a plain list, where removing from the front is O(n) because every remaining element has to shift.
That makes deque the right structure whenever you're implementing a queue, a sliding window, or anything that regularly adds and removes from both sides.
Example: Double-Ended Queue with deque
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0) # O(1) insert at the front
d.append(4) # O(1) insert at the back
print(d)
Dictionary Ordering with OrderedDict
OrderedDict explicitly preserves key insertion order and adds extras like move_to_end() for reordering entries on demand.
Since Python 3.7 plain dicts also preserve insertion order by language guarantee, so OrderedDict is now mainly useful for that extra reordering functionality rather than ordering itself.
Example: Dictionary Ordering with OrderedDict
from collections import OrderedDict
d = OrderedDict()
d["a"] = 1
d["b"] = 2
d.move_to_end("a") # moves "a" to the end without removing it
print(d)
- Reading a missing key on a
defaultdictand being surprised that it creates the key with the default value. - Expecting
Counterto raiseKeyErrorfor missing items, when it returns 0. - Using
list.pop(0)for a queue whendeque.popleft()is much faster.
- Iterators, generators, decorators, and context managers customize how code runs.
- Threading, multiprocessing, and
async/awaithandle concurrent work. - Type hints, dataclasses, enums,
functools, andcollectionsadd useful tools.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: