Glossary

Collections Module

The collections module provides specialised container data types that extend Python's built-in dict, list, set, and tuple. The most commonly used classes are: Counter (a dict subclass for counting hashable objects), defaultdict (a dict that provides a default value for missing keys), OrderedDict (a dict that remembers insertion order — less needed since Python 3.7 dicts are ordered), deque (a double-ended queue with O(1) appends and pops on both ends), and namedtuple (a factory for creating tuple subclasses with named fields).

Counter is particularly versatile: Counter("mississippi") produces {'s': 4, 'i': 4, 'p': 2, 'm': 1}. It supports arithmetic (+, -), most_common(n), and can be used for multiset operations. defaultdict(list) eliminates the common pattern of checking whether a key exists before appending to it. deque is ideal for queues, sliding windows, and bounded buffers.

The collections.abc sub-module provides Abstract Base Classes for containers: Iterable, Iterator, Sequence, MutableSequence, Mapping, MutableMapping, Set, and many more. These ABCs define the expected interfaces for Python's collection protocols and are used extensively in type hints. Understanding collections and collections.abc is essential for writing Pythonic, efficient, and type-safe code.

Related terms: Dictionary, List, Abstract Base Class

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.