Solution Review: Averaging Values in a List

This lesson gives a detailed solution review of how to average values in a list.

Solution: Use the Python len and sum Functions

The solution is fairly straightforward due to Python’s inbuilt functions.

  • Normally, you’d have to iterate over the entire list to sum each element, but Python already has the sum function to do that for you.
  • Similarly, with a single instruction, the len function can determine the size of the list. What’s left then is just to use the basic formula for calculating the average, and divide the sum with the length of the array to obtain the required average.

For example:

Given a list

l = [1,4,9,10,23]
list_sum = sum(l)
list_length = len(l)
average = list_sum/length

The demonstration is given in python code below:

Get hands-on with 1000+ tech skills courses.