Python collections Module
In this page:
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"])
print(counts)
print(counts.most_common(1))
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)
groups["fruits"].append("apple")
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"])
p = Point(1, 2)
print(p.x, p.y)
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)
d.append(4)
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")
print(d)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: