title: Python: Is there a way to get the average of the n newest numbers in an array?
body: <p>I am trying to build a sort of a battery meter, where I have one program that collects voltage samples and adds it to an array. My idea is, that I collect a lot of data when the battery is full, and then build a function that will compare this data with the average of the last 100 or so readings of the voltage as new readings are added every few seconds as long as I don't interrupt the process. </p>
  
  <p>I am using matplotlib to show the voltage output and so far it is working fine: <a href="https://stackoverflow.com/questions/33457040/python-live-graph-update-from-a-changing-text-file/57075813#57075813">I posted an answer here on live changing graphs</a></p>
  
  <p>The voltage function looks like this: </p>
  
  <pre><code>pullData = open("dynamicgraph.txt","r").read() //values are stored here in another function
      dataArray = pullData.split('\n')
      xar = []
      yar = []
  
      averagevoltage = 0
      for eachLine in dataArray:
          if len(eachLine)&gt;=19:
              x,y = eachLine.split(',')
              xar.append(np.int64(x)) //a datetime value
              yar.append(float(y))    //the reading 
      ax1.clear()
      ax1.plot(xar,yar)
      ax1.set_ylim(ymin=25,ymax=29)
      if len(yar) &gt; 1:
          plt.title("Voltage: " + str(yar [-1]) + " Average voltage: "+ str(np.mean(yar)))
  </code></pre>
  
  <p>I am just wondering what the syntax of getting the average of the last x numbers of the array should look like? </p>
  
  <pre><code>if len(yar) &gt; 100
      #get average of last 100 values only
  </code></pre>