all Python 3collectionsterm
collections
module
Specialised containers: Counter, defaultdict, deque, namedtuple, OrderedDict and ChainMap.
Syntax
import collections
It covers tasks where built-in list and dict are awkward: counting (Counter), default values (defaultdict), a queue with fast ends (deque). Abstract container interfaces live in the collections.abc submodule, and typed records are easier with dataclasses. A common mistake is a queue built on list with pop(0): that is O(n), while deque.popleft is O(1).
Examples
from collections import Counter, defaultdict, deque
print(Counter('abracadabra').most_common(1)) # → [('a', 5)]
groups = defaultdict(list)
groups['x'].append(1)
print(dict(groups)) # → {'x': [1]}
print(deque([1, 2, 3], maxlen=2)) # → deque([2, 3], maxlen=2)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy