On this page
  1. collections
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Bounded Sliding Windows & Queues with deque
  7. 2. Layered Configuration Scopes with ChainMap
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes