Python Program to Find Average of a List

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

Problem Description

The program takes the elements of the list one by one and displays the average of the elements of the list.

Problem Solution

1. Take the number of elements to be stored in the list as input.
2. Use a for loop to input elements into the list.
3. Calculate the total sum of elements in the list.
4. Divide the sum by total number of elements in the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to Calculate the Average of Numbers in a Given List. The program output is also shown below.

 
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))
Program 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 upto 2 decimal places.
10. Then the average is printed after rounding.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter the number of elements to be inserted: 3
Enter element: 23
Enter element: 45
Enter element: 56
Average of elements in the list 41.33
 
Case 2:
Enter the number of elements to be inserted: 5
Enter element: 12
Enter element: 24
Enter element: 33
Enter element: 25
Enter element: 18
Average of elements in the list 22.4

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.