Member-only story
Deque, ChainMap, and Counter from the Collections Module
The Python collections module is a treasure trove of specialized data structures designed for specific use cases, offering functionality and memory efficiency beyond standard containers like list, dict, or set. Three standout tools — Deque, ChainMap, and Counter — address unique problems elegantly. Let’s dive into each, with examples and outputs to highlight their power.
1. Deque: The Double-Ended Queue
A deque (pronounced deck) is a list-like container optimized for fast appends and pops from both ends. Whether you’re building a queue, stack, or implementing sliding windows, deques outperform regular lists due to their efficient memory management.
Key Features
• Fast O(1) appends and pops from either end.
• Thread-safe operations.
• Optional maximum length for automatic size control.
Example: Sliding Window
from collections import deque
# Create a deque and manipulate it
dq = deque([1, 2, 3])
print("Initial deque:", dq)
# Append elements
dq.append(4)
dq.appendleft(0)
print("After appends:", dq)
# Pop elements
dq.pop()
dq.popleft()
print("After pops:", dq)
# Output :
# Initial deque: deque([1, 2, 3])
# After appends: deque([0, 1, 2, 3, 4])
# After pops: deque([1, 2…






