We are given a list of numbers and need to find the average of its elements. For example, a = [10, 20, 30, 40], the sum is 100 and the number of elements is 4, so the average is 25.0.
numbers = [10, 20, 30, 40]
total = sum(numbers)
count = len(numbers)
average = total / count
print("Average:", average)
Using sum()
sum() function calculates the total of the list elements, while len() returns the number of elements.
a = [2, 4, 6, 8, 10]
avg = sum(a) / len(a)
print(avg)
Output
6.0
Explanation:
- sum(a) calculates the sum of all elements.
- len(a) returns the number of elements.
- sum(a) / len(a) calculates the average.
Using a Loop
A for loop can be used to calculate the sum manually and then divide it by the number of elements.
a = [2, 4, 6, 8, 10]
total = 0
for val in a:
total += val
avg = total / len(a)
print(avg)
Output
6.0
Explanation:
- total is initialized to 0.
- The loop adds each element to total.
- len(a) gives the number of elements.
- total / len(a) calculates the average.
Using the Statistics Library
statistics.mean() function directly calculates the arithmetic mean of the values.
import statistics
a = [2, 4, 6, 8, 10]
avg = statistics.mean(a)
print(avg)
Output
6
Explanation:
- statistics.mean(a) calculates the arithmetic mean.
- The result is 6 for the given list.
Using numpy.average()
numpy.average() function calculates the average of the elements and is useful when working with numerical data.
import numpy
a = [2, 4, 6, 8, 10]
avg = numpy.average(a)
print(avg)
Output
6.0
Explanation:
- np.average() calculates the average of the elements.
- It returns the result as a floating-point value.
Handling an Empty List
An empty list has no elements, so its average cannot be calculated.
a = []
if a:
avg = sum(a) / len(a)
print(avg)
else:
print("List is empty")
Output
List is empty
Explanation:
- if a checks whether the list contains elements.
- The average is calculated only when the list is not empty.
- The else block handles an empty list.
- This prevents a ZeroDivisionError.
Note: If the list is empty, sum(a) / len(a) raises a ZeroDivisionError because len(a) is 0. Check whether the list contains elements before calculating the average.