title: Running average in Python
body: <p>Is there a pythonic way to <strong>build up a list that contains a running average</strong> of some function?</p>
  
  <p>After reading a fun little piece about <a href="http://www.johndcook.com/Cauchy_estimation.html" rel="nofollow noreferrer">Martians, black boxes, and the Cauchy distribution</a>, I thought it would be fun to calculate a running average of the Cauchy distribution myself:</p>
  
  <pre><code>import math 
  import random
  
  def cauchy(location, scale):
      p = 0.0
      while p == 0.0:
          p = random.random()
      return location + scale*math.tan(math.pi*(p - 0.5))
  
  # is this next block of code a good way to populate running_avg?
  sum = 0
  count = 0
  max = 10
  running_avg = []
  while count &lt; max:
      num = cauchy(3,1)
      sum += num
      count += 1
      running_avg.append(sum/count)
  
  print running_avg     # or do something else with it, besides printing
  </code></pre>
  
  <p>I think that this approach works, but I'm curious if there might be a more elegant approach to building up that <code>running_avg</code> list than using loops and counters (e.g. <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehensions</a>).</p>
  
  <p>There are some related questions, but they address more complicated problems (small window size, exponential weighting) or aren't specific to Python:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/488670/calculate-exponential-moving-average-in-python">calculate exponential moving average in python</a></li>
  <li><a href="https://stackoverflow.com/questions/1174984/how-to-efficiently-calculate-a-running-standard-deviation">How to efficiently calculate a running standard deviation?</a></li>
  <li><a href="https://stackoverflow.com/questions/1319891/calculating-the-moving-average-of-a-list">Calculating the Moving Average of a List</a></li>
  </ul>