a shot of dev knowledge

The goal here is to find the average/mean of a list of numbers. The **average** is the sum of all the numbers in a list divided by its length.

Let’s have a look at a few of the algorithms used to compute the average for a list of numbers.

`sum()`

and `len()`

functionsAn average can be computed using the `sum()`

and `len()`

functions on the list. ** sum()** will return the sum of all the values in the list, which can be divided by the number of elements returned by the

`len()`

function. Take a look at the code below:def Average(l): avg = sum(l) / len(l) return avg my_list = [2,4,6,8,10] average = Average(my_list) print("Average of my_list is", average)

`mean()`

functionThe ** mean() function** in the python

`statistics`

library can be used to directly compute the average of a list. Take a look at the code below:from statistics import mean def Average(l): avg = mean(l) return avg my_list = [2,4,6,8,10] average = Average(my_list) print "Average of my_list is", average

The

`statistics`

library needs to be installed in order to use the`mean()`

function.

from functools import reduce def Average(l): avg = reduce(lambda x, y: x + y, l) / len(l) return avg my_list = [2,4,6,8,10] average = Average(my_list) print "Average of my_list is", average

RELATED COURSES

View all Courses

Keep Exploring

Related Courses