typestar

Moving average in Python

Smoothing a stream of numbers with a sliding window.

from collections import deque

def moving_average(values, window):
    buf = deque(maxlen=window)
    for value in values:
        buf.append(value)
        yield sum(buf) / len(buf)

How it works

  1. A deque with maxlen holds the sliding window.
  2. Each new value pushes the oldest one out.
  3. Yields the running mean after every step.

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
158
Tokens
41
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 25 seconds.

Type this snippet

Step 3 of 7 in Iterators, errors & files, step 46 of 72 in Language basics.

← Previous Next →

Moving average in other languages