maxlen
An optional deque setting that caps its length; once full, adding at one end silently drops an item from the other end.
In more detail
deque(maxlen=3) always holds the three most recent items, which is exactly a sliding window. It behaves like a ring buffer without your having to manage indices. Use it for "last k events" or moving statistics in application code.
Example
window = deque(maxlen=3)Related terms
- deque — A double-ended queue: a sequence that adds and removes items at either end in O(1) time; Python provides it as collections.deque.
- sliding window — The most recent k items of a sequence or stream, which moves forward one item at a time as new data arrives.
- ring buffer — A fixed-size array used as a loop: when writes reach the end they wrap to the start, overwriting the oldest data.
Taught in
- Stacks And Queues: Last In Or First In — Algorithms & Data Structures for Working Engineers
- Deques And Ring Buffers — Algorithms & Data Structures for Working Engineers
- Choosing The Right Sequence — Algorithms & Data Structures for Working Engineers