← Back to Python Course | Chapter 11: Advanced Python | Lesson 12 of 12

Python collections Module

The collections module has special containers that do jobs plain lists and dictionaries do awkwardly, like a tally counter or a line you can join at either end. They make common tasks easier.
Syntax
python
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

python
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

python
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

python
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

python
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

python
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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a missing key on a defaultdict and being surprised that it creates the key with the default value.
  2. Expecting Counter to raise KeyError for missing items, when it returns 0.
  3. Using list.pop(0) for a queue when deque.popleft() is much faster.
Chapter Summary
  • Iterators, generators, decorators, and context managers customize how code runs.
  • Threading, multiprocessing, and async/await handle concurrent work.
  • Type hints, dataclasses, enums, functools, and collections add useful tools.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.