The collections Module in Python
The collections module extends Python's built-in data structures with specialized alternatives suited to particular common needs — a dictionary with a default value for missing keys, a fast double-ended queue, and an automatic item counter, among others already touched on (like namedtuple) elsewhere in this course.
Counter(iterable)
Counts how many times each item appears, returning a dictionary-like object of item-to-count pairs.
defaultdict(default_factory)
Works like a regular dictionary, but automatically creates a default value for any key accessed for the first time, instead of raising a KeyError.
deque — a double-ended queue
Supports fast additions and removals from both ends, unlike a plain list, which is slow to modify at the front.
OrderedDict
Preserves insertion order explicitly — regular dictionaries do this by default since Python 3.7 too, so it’s mostly needed now for its few extra order-related methods.
namedtuple also lives here
Already covered in its own topic, it’s part of this same module.
from collections import Counter, defaultdict, deque votes = ["red", "blue", "red", "green", "blue", "red"]print(Counter(votes)) groups = defaultdict(list)groups["fruits"].append("apple")groups["fruits"].append("banana")print(groups) queue = deque([1, 2, 3])queue.appendleft(0)queue.append(4)print(queue)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.