The main idea of calculating the average of a numeric list (a list that contains only numbers) can be described in two steps:
- Find the total sum of all elements of the list.
- Divide the total sum by the number of elements.
There are several ways to implement these steps with code. Let’s explore the best ones in this quick article.
Using the sum() and the len() functions
This is the most concise approach to get the job done. The sum()
and the len()
functions give you the total and the length of a list, respectively. A TypeError
or ZeroDivisionError
may be raised if the list contains non-numeric elements or is empty.
Example:
numbers = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1]
average = sum(numbers) / len(numbers)
print(average)
Output:
5.96
Performance: The sum()
and len()
functions have a time complexity of O(n)
, where n
is the length of the list. They have a space complexity of O(1)
, as they do not create any new data structures.
Using a for loop
Instead of using convenient built-in functions like in the previous method, you can manually compute the average of a numeric list with a for
loop.
Example:
numbers = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1]
# Initialize total
total = 0
# count the number of items in the list
count = 0
# Iterate over the list
for number in numbers:
# Add each number to the total
total += number
# Increment the count
count += 1
# Calculate the average
average = total / count
print(average)
Output:
5.96
In terms of performance, this approach is similar to the first one. However, when it comes to code conciseness and readability, it lags far behind.