On this page
collections
Prev: codeop | Up: stdlib_module | Next: colorsys
Rel: datetime, zoneinfo, calendar, heapq, bisect
Ref: docs.python.org — collections
Tags: #public #python3 #stdlib
Import
import collections
Overview
Specialized, high-performance container types complementing Python's built-in dict, list, set, and tuple. Reach for Counter for frequency tallying, defaultdict for grouping/accumulating without key-existence boilerplate, deque for O(1) queues and sliding windows, and ChainMap for layered configuration scopes.
Quick Start
from collections import Counter, defaultdict, deque
counts = Counter("abracadabra")
assert counts.most_common(2) == [("a", 5), ("b", 2)]
groups: defaultdict[str, list[str]] = defaultdict(list)
for word in ("apple", "apricot", "banana"):
groups[word[0]].append(word)
assert groups["a"] == ["apple", "apricot"]
Implementation Walkthrough
1. Bounded Sliding Windows & Queues with deque
list.pop(0) is O(n); deque gives O(1) appends/pops on both ends and automatically evicts old items when maxlen is set:
from collections import deque
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
assert list(recent) == [2, 3, 4]
2. Layered Configuration Scopes with ChainMap
Lookups search mappings in order without copying dictionaries; writes mutate only the first mapping:
from collections import ChainMap
defaults = {"host": "localhost", "port": 8000, "debug": False}
env_overrides = {"port": 9000}
cli_overrides = {"debug": True}
config = ChainMap(cli_overrides, env_overrides, defaults)
assert config["host"] == "localhost"
assert config["port"] == 9000
assert config["debug"] is True
Gotchas & Boundaries
defaultdictinserts on read: Checkingd[missing_key]creates and stores a default value; usekey in dord.get(key)when you only want to inspect.Counterreturns0for missing keys (without inserting), and subtracting counters with-drops zero/negative counts (use.subtract()if you need negative values).- Prefer
@dataclass(frozen=True)overnamedtupleunless you specifically need tuple unpacking ortuplesubclassing. - Plain
dictpreserves insertion order (Python 3.7+): Only reach forOrderedDictwhen you need.move_to_end()or order-sensitive equality (od1 == od2).
Common Functions
- collections.namedtuple() —
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)— Returns a new subclass of tuple with named fields.
Classes & Objects
- collections.ChainMap — A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. (Methods:
.clear(),.copy(),.fromkeys(),.get(),.items(),.keys()) - collections.Counter — Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. (Methods:
.clear(),.copy(),.elements(),.fromkeys(),.get(),.items()) - collections.defaultdict — The default factory is called without arguments to produce a new value when a key is not present, in getitem only. (Methods:
.clear(),.copy(),.fromkeys(),.get(),.items(),.keys()) - collections.deque — A list-like sequence optimized for data accesses near its endpoints. (Methods:
.append(),.appendleft(),.clear(),.copy(),.count(),.extend()) - collections.OrderedDict — Dictionary that remembers insertion order (Methods:
.clear(),.copy(),.fromkeys(),.get(),.items(),.keys()) - collections.UserDict —
collections.UserDictclass. (Methods:.clear(),.copy(),.fromkeys(),.get(),.items(),.keys()) - collections.UserList — A more or less complete user-defined wrapper around list objects. (Methods:
.append(),.clear(),.copy(),.count(),.extend(),.index()) - collections.UserString —
collections.UserStringclass. (Methods:.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/bisect
- tuts/python3/stdlib_module/calendar
- tuts/python3/stdlib_module/codeop
- tuts/python3/stdlib_module/collections/ChainMap
- tuts/python3/stdlib_module/collections/Counter
- tuts/python3/stdlib_module/collections/defaultdict
- tuts/python3/stdlib_module/collections/deque
- tuts/python3/stdlib_module/collections/namedtuple
- tuts/python3/stdlib_module/collections/OrderedDict
- tuts/python3/stdlib_module/collections/UserDict
- tuts/python3/stdlib_module/collections/UserList
- tuts/python3/stdlib_module/collections/UserString
- tuts/python3/stdlib_module/colorsys
- tuts/python3/stdlib_module/copy
- tuts/python3/stdlib_module/datetime
- tuts/python3/stdlib_module/enum
- tuts/python3/stdlib_module/graphlib
- tuts/python3/stdlib_module/heapq
- tuts/python3/stdlib_module/pprint
- tuts/python3/stdlib_module/reprlib
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/types
- tuts/python3/stdlib_module/weakref
- tuts/python3/stdlib_module/zoneinfo
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators
- tuts/python3/tutorials/core_fundamentals/builtin_data_structures
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modern_data_modeling
- tuts/python3/tutorials/popular_application_domains/data_science_and_machine_learning
Related notes
- tuts/python3/stdlib_module/bisect Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codeop Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/ChainMap Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/Counter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/defaultdict Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/deque Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/namedtuple Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/OrderedDict Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/UserDict Linked here; links to this page; shared tags: #stdlib