deque maxlen Keeps Recent Events
Track recent events with a bounded deque: maxlen evicts the oldest end automatically, both ends are O(1), and rotate shifts the whole window in place.
Code
from collections import deque
# deque(maxlen=N):固定容量事件窗口,超限时最旧一端自动滑出
recent = deque(maxlen=3)
for event in ["boot", "login", "upload", "logout"]:
recent.append(event)
print(list(recent))
# 两端操作 O(1):popleft 不搬移整个列表
first = recent.popleft()
print("popped:", first, "| left:", list(recent))
# rotate(n):正数右移、负数左移,轮转调度的一等原语
rotation = deque([1, 2, 3, 4])
rotation.rotate(1)
print("right :", list(rotation))
rotation.rotate(-2)
print("left :", list(rotation))Output
Captured from a sandboxed run of this snippet in the build pipeline.
['boot']
['boot', 'login']
['boot', 'login', 'upload']
['login', 'upload', 'logout']
popped: login | left: ['upload', 'logout']
right : [4, 1, 2, 3]
left : [2, 3, 4, 1]What the code does
Repetition is confined to for event in ["boot", "login", "upload", "logout"] — the rest of the file is straight-line.
Module-level bindings hold the data — recent, first, rotation — with no function scope in between.
Using it
Output lines are prefixed (popped:, right :, left :), making each step’s effect easy to spot.
Key statements
for event in ["boot", "login", "upload", "logout"]:
recent.append(event)
print(list(recent))
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `collections`. Its state lives in module-level bindings: `recent`, `first`, `rotation`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.