Average list Python

How to take the average of a list in Python

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.

Algorithms

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

1. Using sum[] and len[] functions

An 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]

Run

2. Using the mean[] function

The 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.

3. Using reduce[] and lambda functions

The reduce method can be used to loop through the list and the sum can be computed in the lambda function. The number of elements can be obtained using len[].

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

Run

Video liên quan

Chủ Đề