Python Program to calculate the average of numbers in a list


March 21, 2022, Learn eTutorial
1351

In this simple python program, we need to find the average of numbers. It is a beginner-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

How to find the average of numbers in python?

In this simple python program on the list, we have to calculate the average for the numbers in a list. For calculating the average of numbers, we need to take the sum of the numbers in the list and divide the sum by the number of elements in the list.

Let us take an example as we have some numbers 1, 2, 3, 4, 5 now we take the average by calculating the sum 1+2+3+4+5 = 15. and now we are taking the average by dividing the sum by the number of elements. as 15 / 5 = 3.

In this simple python program, we have to add the elements from the user using a for loop in python. we introduce a method called python list append(). The list append method in python is for adding an element to the list.

The syntax for the append method is list.append(item)

where the item is added to the list. Append has one parameter called item, which is the element that is to be added to the list in python language. Item can be anything as strings or numbers or anything.

ALGORITHM

STEP 1: Input the number of elements in the list using the input method in python language and use an int to convert the string to an integer.

STEP 2: Initialize a list.

STEP 3: Use a for loop using the range method from zero to number elements in the list.

STEP 4: Enter the elements using the input method and convert them to an integer using int in python language and add it to the list using the append method.

STEP 5: Calculate the average by taking the sum of the elements of the list and divide the sum by the number of elements in the list.

STEP 6: Print the average of the python list using the print method.

Note: We are using a round built-in function in python programming to round the digits of a float number to a rounded value.

Python Source Code

                                          n=int(input("Enter the number of elements to be inserted: "))

a=[]

for i in range(0,n):

    elem=int(input("Enter the element to the list: "))

    a.append(elem)

avg=sum(a)/n

print("Average of elements in the list", round(avg,2))
                                      

OUTPUT

Enter the number of elements to be inserted: 5
Enter element: 1
Enter element: 2
Enter element: 3
Enter element: 4
Enter element: 5

Average of elements in the list : 3