Python collections: deque, OrderedDict, and ChainMap
Beyond defaultdict and Counter, the collections module has deque for fast queues, OrderedDict for ordered dicts, and ChainMap for layered lookups. The collections module is best known for defaultdict and Counter , which I covered previously. But it also contains deque , OrderedDict , and ChainMap , each solving a specific problem that lists and dicts handle poorly. I reach for these less often, but when I do, there is no clean alternative. deque for Fast Queue Operations A deque (double-ended queue) supports fast append and pop from both ends. Lists support append and pop at the end in O(1), but inserting or removing from the front is O(n) because every element shifts. The deque does both in O(1). from collections import deque # A queue: add to right, remove from left queue = deque() queue.append('task1') queue.append('task2') next_task = queue.popleft() # 'task1' # A stack: add and remove from right stack = deque() stack.append('item') stack.pop() # Bounded deque: keeps last N items recent = deque(maxlen=5) for i in range(10): recent.append(i) # deque([5, 6, 7, 8, 9], maxlen=5) The maxlen parameter creates a bounded deque that automatically discards old items when full.…