Double-ended queues
Process work items from either side of a buffer.
Python · Module
Python’s collections module provides specialized container types as alternatives to built-in dict, list, set, and tuple. It includes tools for queues, counting, layered mappings, named records, default values, and container subclassing.
The collections module supplies specialized alternatives to built-in containers. Its types cover named tuple records, double-ended queues, layered mappings, counting, insertion-aware dictionaries, factories for missing values, and wrappers that simplify container subclassing.
import collections
from collections import namedtuple, deque, ChainMap, Counter, OrderedDict, defaultdict, UserDict, UserListfrom collections import Counter, defaultdict, deque
queue = deque(["job-1", "job-2"])
queue.append("job-3")
print(queue.popleft())
counts = Counter(["python", "python", "go"])
print(counts["python"])
settings = defaultdict(list)
settings["tags"].append("backend")
print(settings["tags"])This runnable example uses a deque for efficient end operations, Counter to tally hashable values, and defaultdict to create a list automatically for a missing key.
Process work items from either side of a buffer.
Aggregate frequencies for hashable values.
Combine configuration layers while retaining precedence.
Group values under keys without manual initialization.
collections provides specialized container types that extend or complement dict, list, set, and tuple. Examples include deque, Counter, defaultdict, ChainMap, and namedtuple().
Follow-up: When is deque preferable to list? Use it when frequent appends and pops are needed at both ends, because it is designed for efficient end operations.
deque is a list-like double-ended queue. It supports fast appends and pops on either end, while indexed access becomes slower toward the middle.
Follow-up: How can deque memory be bounded? Construct it with maxlen; when full, adding new items discards items from the opposite end.
Counter is a dict subclass for counting hashable objects. defaultdict is a dict subclass that calls a factory function to provide missing values.
Follow-up: How does defaultdict differ from dict.get()? defaultdict can create and store a value through its factory when a missing key is accessed; get() does not invoke that factory.
namedtupledequeChainMapCounterOrderedDictdefaultdictUserDictUserList