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.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 15 views 0 copies

Python code

26 lines
Python 3.9+
from 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

stdout
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

  1. Use `statistics.mean` on a `collections.deque` slice if performance is less critical
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.