Python Practice › Collections Programs › Program 11
Moving average with deque
Write a Python program to compute a moving average over a window of 3 values.
Output
[20.0, 30.0, 40.0]
Approach
- Keep the window in a deque with maxlen and average it each step.
Solution
from collections import deque values = [10, 20, 30, 40, 50]window = deque(maxlen=3)averages = []for v in values: window.append(v) if len(window) == 3: averages.append(sum(window) / 3)print(averages)Output
[20.0, 30.0, 40.0]
Learn the concept
New to this topic? Read the lesson, then come back.