Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Data Structures and Functional Tools

The collections module

Reference for Python's collections module: Counter, defaultdict, deque, namedtuple, OrderedDict and ChainMap, when to use each and common pitfalls.

The collections module extends Python's built-in list, dict, set and tuple with specialized containers that solve common problems with less code: counting items, grouping values, fast queues, tuples with named fields and layered lookups.

You rarely need all of them at once. Reach for Counter when you count, defaultdict when you group, deque when you add or remove at both ends, and namedtuple for small read-only records (though dataclasses is often better for anything with behavior). The classes are covered in detail on their own pages; this page is the map.

Python
from collections import Counter

print(Counter("mississippi").most_common(2))
# [('i', 4), ('s', 4)]

Try it

Python Counter, defaultdict and deque

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python namedtuple, OrderedDict and ChainMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What is in the module

Name What it is Typical use
Counter dict subclass that counts hashable items; missing keys count as 0. Word frequencies, tallies, comparing multisets.
defaultdict dict that creates a default value on first access to a missing key. Grouping, building lists or sets per key.
deque Double-ended queue with O(1) appends and pops at both ends. Queues, sliding windows, breadth-first search.
namedtuple Factory for tuple subclasses with named fields. Lightweight immutable records.
OrderedDict dict with order-sensitive equality and move_to_end(). LRU caches, order-dependent comparisons.
ChainMap A view over several mappings searched in order. Layered settings, scoped variables.
UserDict, UserList, UserString Wrapper classes designed for subclassing. Custom containers with predictable behavior.

The abstract base classes (Mapping, Sequence, Iterable and so on) live in collections.abc; the old aliases directly under collections were removed in Python 3.10.

Usage notes

  • Import ABCs from collections.abc. from collections import Mapping fails on modern Python.
  • Ordinary dict keeps insertion order since Python 3.7. OrderedDict remains useful for move_to_end(), popitem(last=False) and equality that considers order.
  • defaultdict creates keys on lookup. Merely reading d["missing"] inserts the key. Use d.get(key) or key in d when you do not want that.
  • deque indexing in the middle is O(n). It is built for the ends. Use a list for random access.
  • Counter values can be zero or negative. Arithmetic like c1 - c2 drops results that are not positive; use subtract() to keep them.
  • namedtuple fields are read-only. Use _replace() to get a changed copy. For mutable records or defaults, use dataclasses or typing.NamedTuple.
  • Pickling and JSON. Counter, defaultdict and OrderedDict serialize through dict(...) for JSON; deque needs list(...).