Skip to main content

collections

Container datatypes beyond the built-ins: ordered/default dicts, counters, deques, named tuples, chain maps, and user-extensible bases. The collections.abc submodule houses the abstract base classes for the container protocols.

Source-of-record: Lib/collections/__init__.py, Modules/_collectionsmodule.c, collections docs.

Counter

Counter(iterable_or_mapping=None, **kwargs)

Multiset / frequency map. Subclass of dict.

MethodBehaviour
c.elements()Iterator of elements repeated by count.
c.most_common(n=None)[(elem, count), ...] sorted descending.
c.subtract(other)Element-wise subtraction; can go negative.
c.update(other)Element-wise addition.
c.total()Sum of counts (3.10+).
c + c2, c - c2Multiset add / subtract (drops non-positive).
c | c2, c & c2Multiset union (max) / intersection (min).
+c, -cDrop non-positive / non-negative counts.

OrderedDict

dict subclass that preserved insertion order even before 3.7 made the plain dict order-stable. Still distinct because of:

MethodBehaviour
od.move_to_end(key, last=True)Reorder.
od.popitem(last=True)LIFO by default; last=False for FIFO.
EqualityOrder-sensitive between two OrderedDicts.

defaultdict

defaultdict(default_factory=None, /, *args, **kwargs)

Provides a default value via default_factory() on missing keys.

AttributeMeaning
dd.default_factoryZero-arg callable; missing keys call it.
dd[k]Inserts default_factory() if missing.
dd.__missing__(k)Hook the lookup uses.

deque

deque(iterable=(), maxlen=None)

Doubly-linked list-like container with O(1) appends/pops at both ends.

MethodBehaviour
append(x) / appendleft(x)Push.
pop() / popleft()Pop.
extend(it) / extendleft(it)Bulk push (note: extendleft reverses).
rotate(n=1)Rotate right (or left if negative).
clear(), copy(), count(x), index(x[, start[, stop]]), insert(i, x), remove(x), reverse()Stdlib operations.
maxlenRead-only cap.

ChainMap

ChainMap(*maps)

Composes several mappings into one view. Writes go to the first map; reads cascade through the chain.

Method / attrRole
mapsList of underlying mappings.
new_child(m=None)Push a fresh mapping (or m) onto the chain.
parentsView without the first mapping.

namedtuple

collections.namedtuple(typename, field_names, *, rename=False,
defaults=None, module=None)

Generates a tuple subclass with named fields.

Generated memberNotes
T._fieldsField names.
T._field_defaultsDefaults dict.
t._asdict()Dict view.
t._replace(**changes)Returns a new tuple with fields replaced.
T._make(iterable)Construct from iterable.

UserList, UserDict, UserString

Subclassable wrappers around list, dict, str. Useful where subclassing the built-in is awkward (mutators may bypass the wrapper).

collections.abc

Re-exports the ABCs from _collections_abc:

GroupABCs
HashableHashable.
IterableIterable, Iterator, Generator, Reversible, Collection.
ContainersContainer, Sized.
SequenceSequence, MutableSequence, ByteString (deprecated 3.12).
SetSet, MutableSet.
MappingMapping, MutableMapping, MappingView, KeysView, ValuesView, ItemsView.
CallableCallable.
AsyncAwaitable, Coroutine, AsyncIterable, AsyncIterator, AsyncGenerator.
Buffer (3.12)Buffer.

Gopy status

AreaState
Counter, OrderedDict, defaultdictComplete.
dequeComplete; C-fast path in module/_collections.
ChainMapComplete.
namedtupleComplete.
collections.abc ABCsComplete.

Reference

  • CPython 3.14: collections.
  • Lib/collections/, Modules/_collectionsmodule.c.
  • module/collections/, module/_collections/. gopy port.