Solution Review: Averaging Values in a List
This lesson gives a detailed solution review of how to average values in a list.
We'll cover the following
Solution: Use the Python
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
sumfunction to do that for you.
- Similarly, with a single instruction, the
lenfunction 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.
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: