# How to calculate Average of a stream of numbers by program in Python

In this tutorial, we will see how can we calculate the Average of a stream of numbers in Python.

Average is also known as the mean. Average or mean are terms related to mathematics and statistics. The average value is the central value of a set of numbers.

To calculate the average of a group of numbers we add all the numbers (Arithmetic Addition) and then divide it by the length of the group of numbers.

We are clear with the concept of average, let’s see how can we find average in Python.

### 1. Using a loop

def avg(numbers): sumofnum=0 totalnum=len(numbers) for i in numbers: sumofnum+=i average=sumofnum/totalnum print("Average value is:",average) numbers=[1,54,22,60,7] avg(numbers)

OUTPUT: Average value is: 28.8

### 2. Using Python functions

def avg(numbers): average=sum(numbers)/len(numbers) print("Average value is:",average) numbers=[1,54,22,60,7] avg(numbers)

OUTPUT: Average value is: 28.8

### 3. Using a numpy array

import numpy as np def avg(numbers): numbers=np.array(numbers) average=numbers.mean() print("Average value is:",average) numbers=[1,54,22,60,7] avg(numbers)

OUTPUT: Average value is: 28.8

### 4. Average between two given position

def avg(numbers,start,end): sumofnum=0 totalnum=end-start+1 for i in range(start-1,end): sumofnum+=numbers[i] average=sumofnum/totalnum print("Average value is:",average) numbers=[1,54,22,60,7] avg(numbers,2,5)

OUTPUT: Average value is: 35.75

### 5. Average value at each position in the array

def avg(numbers): sumofnum=0 for i in range(0,len(numbers)): sumofnum+=numbers[i] average=sumofnum/(i+1) print("Average value at position"+str(i+1)+"is:",average) numbers=[1,54,22,60,7] avg(numbers)

OUTPUT: Average value at position1 is: 1.0 Average value at position2 is: 27.5 Average value at position3 is: 25.666666666666668 Average value at position4 is: 34.25 Average value at position5 is: 28.8

Hope you liked this tutorial!

## Leave a Reply