Python Program to Calculate the Average of an Array

Write a Python program to calculate the average of an array or Numpy array of elements. The Python Numpy module has the sum and average methods to find the sum and average of array items.

import numpy as np

arr = np.array([10, 20, 40, 60, 80, 100])

total = arr.sum()
avg = np.average(arr)

print('\nThe Sum Of Array Elements     = ', total)
print('\nThe Average Of Array Elements = ', avg)
Python Program to Calculate the Average of an Array

This python program uses for loop to iterate Numpy Array items and calculates the sum and average of all elements.

import numpy as np

arr = np.array([14, 25, 35, 67, 89, 11, 99])
total = 0

for i in range(len(arr)):
    total = total + arr[i]

avg = total / len(arr)

print('\nThe Sum Of Array Elements     = ', total)
print('\nThe Average Of Array Elements = ', avg)
The Sum Of Array Elements     =  340

The Average Of Array Elements =  48.57142857142857

Python program to calculate the average of an array using a while loop

import numpy as np

arr = np.random.randint(10, 150, size = 11)

print('The Random Array Genegrated')
print(arr)

total = 0
i = 0

while i < len(arr):
    total = total + arr[i]
    i = i + 1

avg = total / len(arr)

print('\nThe Sum Of Array Elements     = ', total)
print('\nThe Average Of Array Elements = ', avg)
The Random Array Genegrated
[123  91 119 131  45 121  48  53  44  60  82]

The Sum Of Array Elements     =  917

The Average Of Array Elements =  83.36363636363636

This Python example allows to enter array elements and finds the sum and average of all array items.

import numpy as np

arrlist = []
Number = int(input("Total Array Elements to enter = "))

for i in range(1, Number + 1):
    value = int(input("Please enter the %d Array Value = "  %i))
    arrlist.append(value)


arr = np.array(arrlist)

total = 0

for i in range(len(arr)):
    total = total + arr[i]

avg = total / len(arr)

print('\nThe Sum Of Array Elements     = ', total)
print('\nThe Average Of Array Elements = ', avg)
Total Array Elements to enter = 7
Please enter the 1 Array Value = 22
Please enter the 2 Array Value = 44
Please enter the 3 Array Value = 66
Please enter the 4 Array Value = 88
Please enter the 5 Array Value = 99
Please enter the 6 Array Value = 122
Please enter the 7 Array Value = 154

The Sum Of Array Elements     =  595

The Average Of Array Elements =  85.0