Counter stores counts by key, while deque stores ordered entries with endpoint operations suited to queues and rolling histories.
Python Counter and deque: counts, queues and bounded history
Operation contract
The audit history retains the last two receipt IDs. Its maxlen causes an older entry to be discarded when a third arrives, so this is a rolling display rather than a durable event log. Counter separately counts review outcomes. The sorted output defines presentation order instead of relying on how outcome keys happened to enter the import.
Failure and ownership boundary
A bounded deque discards evidence by design. It should not replace a financial ledger or retry queue that must retain every outstanding job. Counter also permits zero and negative counts; its contents do not by themselves establish a nonnegative inventory invariant. Python inventory project: validate a batch before replacing stored state and Python asyncio.Queue: backpressure and completion accounting provide the missing contracts.
Working program
from collections import Counter, deque
recent_receipts = deque(maxlen=2)
for receipt_id in (41, 42, 43):
recent_receipts.append(receipt_id)
outcomes = Counter(["accepted", "rejected", "accepted"])
print(list(recent_receipts))
print(sorted(outcomes.items()))
print(outcomes["missing"])Output
[42, 43]
[('accepted', 2), ('rejected', 1)]
0Costs and limits
For n outcomes with u distinct keys, counting uses expected O(n) dictionary work and O(u) retained keys. Endpoint deque operations avoid shifting an entire list; the rolling history stores at most its declared capacity.
Common Mistakes
- maxlen discards old entries; it does not reject new work.
- A Counter is not a validated nonnegative stock ledger.
Connected lessons
Python dictionaries: insertion order and duplicate-key replacement, Python heapq top-k: define ties before ranking frequencies, Python asyncio.Queue: backpressure and completion accounting.
Check this related boundary
Python exercise: reconcile duplicate receipt counts without losing multiplicity.
Trace the related workflow
Python exercise: encode consecutive states without merging distant runs.
