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.
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))
- User must first enter the number of elements which is stored in the variable n.
- 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.
- Then, the element that the user enters is stored in the variable elem.
- a.append(elem) appends the element to the list.
- Now the value of i is incremented to 2.
- The new value entered by the user for the next loop iteration is now stored in elem which is appended to the list.
- The loop runs till the value of i reaches n.
- 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.
- round(avg,2) rounds the average up to 2 decimal places.
- Then the average is printed after rounding.