Back
+20 XP
Concept

Circular Buffers with collections.deque(maxlen)

`collections.deque(maxlen=N)` implements a high-performance circular ring buffer in C. Once full, pushing new elements automatically evicts the oldest elements from the opposite side in $O(1)$ 🔄.

python
from collections import deque

# Ring buffer of size 3:
buffer = deque(maxlen=3)

for i in range(5):
    buffer.append(f"log_{i}")
    print(list(buffer))  # Evicts log_0, log_1 automatically! 🔄

# 4. Circular Buffers with collections.deque(maxlen) `collections.deque(maxlen=N)` implements a high-performance circular ring buffer in C. Once full, pushing new elements automatically evicts the oldest elements from the opposite side in $O(1)$ 🔄. ```python from collections import deque # Ring buffer of size 3: buffer = deque(maxlen=3) for i in range(5): buffer.append(f"log_{i}") print(list(buffer)) # Evicts log_0, log_1 automatically! 🔄 ``` Ring buffers are the bedrock of telemetry streaming, financial order books, and real-time dashboard logs where you only care about the latest $N$ measurements! 🔄 --- ### Question What happens when you append to a `deque` that has already reached its `maxlen` capacity? 🧠 - [ ] a. It automatically discards the oldest element from the opposing end in $O(1)$ time 🔄 - [ ] b. It raises an `OverflowError` exception - [ ] c. It reallocates memory and doubles the maxlen - [ ] d. It converts the deque into a static tuple --- ### Challenge Create `buffer = deque(maxlen=2)`. Append `'A'`, `'B'`, and `'C'`. Print `list(buffer)`. 🎯 <details> <summary>Solution</summary> ```python from collections import deque buffer = deque(maxlen=2) buffer.append("A") buffer.append("B") buffer.append("C") print(list(buffer)) ``` </details>

Checkpoint

What happens when you append to a `deque` that has already reached its `maxlen` capacity? 🧠

Practice

Create `buffer = deque(maxlen=2)`. Append `'A'`, `'B'`, and `'C'`. Print `list(buffer)`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks