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

Python Lists

Lists are one of the most important data structures in Python. They are used to store a sequence of items, similar to an Array in other languages. However, unlike arrays, lists are dynamic and can grow and shrink as needed.

Program Code

# Take the number of elements to be stored in the list as input
n = int(input("Enter number of elements in list: "))

# Use a for loop to input elements into the list
a = []
for i in range(0, n):
    elem = int(input("Enter element: "))
    a.append(elem)

# Calculate the total sum of elements in the list
total = sum(a)

# Divide the sum by total number of elements in the list
avg = total / n

# Print the result
print("Average of elements in the list: ", round(avg, 2))

Input Given:

Enter number of elements in list: 5
Enter element: 10
Enter element: 20
Enter element: 30
Enter element: 15
Enter element: 25

Expected Output:

Average of elements in the list: 20.0

Code Explanation

  1. We take the number of elements to be stored in the list as input from the user.
  2. We use a for loop to input elements into the list.
  3. We calculate the total sum of elements in the list.
  4. We divide the sum by the total number of elements in the list.
  5. We print the result.

Leave a Comment

Share to...