How to Implement a Sliding Window Average in Python
Compute the average of the most recent N values in a stream using a bounded deque, efficiently updating the total as new values arrive.
Python code
26 linesfrom collections import deque
class SlidingWindowAverage:
def __init__(self, window_size):
self.window_size = window_size
self.window = deque(maxlen=window_size)
self.total = 0
def add(self, value):
if len(self.window) == self.window_size:
self.total -= self.window[0]
self.window.append(value)
self.total += value
def average(self):
if not self.window:
return 0.0
return self.total / len(self.window)
if __name__ == "__main__":
swa = SlidingWindowAverage(3)
for value in [10, 20, 30, 40, 50]:
swa.add(value)
print(f"Added {value:>2}, average: {swa.average():.1f}")
Output
Added 10, average: 10.0
Added 20, average: 15.0
Added 30, average: 20.0
Added 40, average: 30.0
Added 50, average: 40.0
How it works
The deque(maxlen=window_size) automatically discards the oldest item when the window is full, keeping only the most recent N values. Each add call adjusts self.total by subtracting the evicted value (if any) and adding the new value, so the average is computed in O(1) time instead of summing the window each time. The average method guards against an empty window by returning 0.0. This pattern is ideal for streaming data where you need a rolling statistic without storing the entire history.
Common mistakes
- Forgetting to subtract the evicted element from `self.total` before appending
- Using a plain list and slicing `[-window_size:]`, which is O(N) per call
- Not handling the empty window case, causing a ZeroDivisionError
- Confusing the deque's maxlen behavior with manual padding logic
Variations
- Use `statistics.mean` on a `collections.deque` slice if performance is less critical
- Implement a ring buffer with a fixed-size list and modulo indexing for lower-level control
Real-world use cases
- Tracking the average latency of recent HTTP requests to a service in a metrics agent.
- Computing rolling CPU or memory usage averages in a system monitoring script.
- Averaging the latest N sensor readings to smooth out noise in an IoT data pipeline.
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.