
🔄 The Python Collection Almost Nobody Uses (But Should)#
Python’s deque from collections is perfect for real-time sliding windows. 🚀
🔍 What is deque?#
deque (double-ended queue, pronounced “deck”) is a fixed-size collection. When it’s full and you append a new element, the oldest one is automatically removed — perfect FIFO.
from collections import deque
# Sliding window of 3 elements
window = deque(maxlen=3)
window.append(1) # [1]
window.append(2) # [1, 2]
window.append(3) # [1, 2, 3]
window.append(4) # [2, 3, 4] ← 1 was dropped💡 Why Not Just Use Lists?#
With lists: list.pop(0) is O(n) — shifts all elements.
With deque: operations at both ends are O(1).
🎯 Perfect Use Cases#
- 📊 Moving average on sensor data or time series
- 🔔 Anomaly detection in time windows
- 🌊 Real-time stream processing
- 📈 Technical indicators in trading (RSI, MACD)
💡 Explanation in a nutshell#
Python’s deque (collections.deque) is a double-ended queue with configurable maximum size. When the queue is full and a new element is appended, the oldest one is automatically removed (FIFO). Its insertion/removal operations at both ends are O(1) — much more efficient than lists for implementing real-time sliding windows or fixed-size buffers.
More information at the link 👇
Also published on LinkedIn.

