Python program to calculate the average of all the elements in a list

In this tutorial, we are going to show how to calculate the average of all the elements in a list in Python by using different methods. As well as average is calculated by the sum of the element is divided by the total number of elements.

Mathematical statistics functions to calculate the average of all the elements in a list

Explanation:

  1. mean() functions calculate an average of the sample.
  2. defining list.
  3. printing an average of all the elements in a list.
from statistics import mean
listA=[1,2,3,5,6,6]
print("average of all the elements:",mean(listA))

Output:

average of all the elements: 3. 8333333333333335

Sum() and len() function to calculate the average of all the elements in a list in Python

Explanation:

  1. defining list.
  2. print the sum of all elements present in the list and Using sum() function we can get the sum of the list.
  3. print the length of the list and len() function is used to get the number of elements in a list.
  4. when ((sum(listA))/(len(listA))) done. The value stored in the avg variable.
  5. printing an average of all the elements in a list.
listA=[5,29,19,8,52,66,5,31]
print("sum of element:",sum(listA))
print("length of list:",len(listA))
avg=((sum(listA))/(len(listA)))
print("average of all the elements:",avg)

Output:

sum of element: 215
length of list: 8
average of all the elements: 26.875

User input and append function to calculate the average of all the elements in a list:-

Explanation:

  1. initialize x is a list type variable.
  2. n is the int type variable that stores the size of the list.
  3. after taking a value of n’ enters the element in a list.
  4. for loop which executes till n-1.
  5. b is an int type variable that stores a single value at a time.
  6. variable b append the value in list x.
  7. printing list x.
  8. invariable c the sum of the list stored.
  9. print the sum of all elements present in the list and Using sum() function we can get the sum of the list.
  10.  c divides n ie sum of a list divided by length/size of the list.
  11. printing average of all the elements in a list.
x=list()
n=int(input("enter the size of list:"))
print("enter the element in list:")
for a in range(n):
    b=int(input(""))
    x.append(int(b))
print("list is",x) 
c=sum(x)
print("sum of list is:",c)  
d=c/n
print("average of all the elements:",d)

Output:

enter the size of list:5
enter the element in list:

23

65

89

65

3
list is [23, 65, 89, 65, 3]
sum of list is: 245
average of all the elements: 49.0

You may also read:

Leave a Reply