time series calculation in list comprehension?

Lonnie Princehouse finite.automaton at gmail.com
Fri Mar 10 21:35:50 CET 2006

Well, you could iterate over an index into the list:

  from __future__ import division

  def moving_average(sequence, n):
      return [sum(sequence[i:i+n])/n for i in

Of course, that's hardly efficient.  You really want to use the value
calculated for the i_th term in the (i+1)th term's evaluation.  While
it's not easy (or pretty) to store state between iterations in a list
comprehension, this is the perfect use for a generator:

  def generator_to_list(f):
    return lambda *args,**keywords: list(f(*args,**keywords))

  def moving_average(sequence, n):
    assert len(sequence) >= n and n > 0
    average = sum(sequence[:n]) / n
    yield average
    for i in xrange(1, len(sequence)-n+1):
      average += (sequence[i+n-1] - sequence[i-1]) / n
      yield average

More information about the Python-list mailing list