A deque with maxlen retains a fixed number of items and discards an item from the opposite end when full.
Make this comfortable
Python bounded deque: append silently evicts the opposite end
Observed contract
An operations display keeps three recent receipt IDs. Appending a fourth removes the oldest left item. Inserting an older correction at the left then removes the rightmost item; the two directions have different eviction victims.
Boundary
This structure is a recent-events view, not an audit trail. Eviction is silent and permanent unless another owner stores the record. A bounded deque also rejects indexed insertions that would exceed its limit; it is not a general fixed-capacity queue protocol.
Executable case
from collections import deque
recent_receipts = deque(["R-47", "R-48", "R-49"], maxlen=3)
recent_receipts.append("R-50")
print("after_new", list(recent_receipts))
recent_receipts.appendleft("R-46")
print("after_correction", list(recent_receipts))
print("capacity", recent_receipts.maxlen)Output
after_new ['R-48', 'R-49', 'R-50']
after_correction ['R-46', 'R-48', 'R-49']
capacity 3Cost
Appending at either end is approximately O(1), and retained references are bounded by maxlen. Looking up a middle index costs linear time, so use a list or dictionary for repeated random access.
Common Mistakes
- A bounded deque does not tell the caller which item it dropped.
- appendleft evicts from the right when full.
- Do not use this view as the only copy of financially significant events.
Connected lessons
python
deque-maxlen-eviction
