by BehindJava

Write a program to Calculate the Average of Numbers in a Given List in Python

Home » python » Write a program to Calculate the Average of Numbers in a Given List in Python

In this tutorial we are going to learn about Calculate the Average of Numbers in a Given List in Python.

Python Program to Calculate the Average of Numbers in a Given List

n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
    elem=int(input("Enter element: "))
    a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))

Explanation

  1. User must first enter the number of elements which is stored in the variable n.
  2. The value of I ranges from 0 to the number of elements, and is incremented each time after the body of the loop is executed.
  3. Then, the element that the user enters is stored in the variable elem.
  4. a.append(elem) appends the element to the list.
  5. Now the value of i is incremented to 2.
  6. The new value entered by the user for the next loop iteration is now stored in elem which is appended to the list.
  7. The loop runs till the value of i reaches n.
  8. sum(a) gives the total sum of all the elements in the list and dividing it by the total number of elements gives the average of elements in the list.
  9. round(avg,2) rounds the average up to 2 decimal places.
  10. Then the average is printed after rounding.