ID : 249

viewed : 256

Tags : PythonPython List

97

This tutorial introduces how to find the average of a list in Python. It also lists some example codes to further clarify the concept as the methods have changed from previous versions of Python.

`statiscics`

Library to Get the Average of a ListIf you are using Python 3.4+, you can use newly introduced library. This library contains multiple mathematical functions that can be used straightforwardly. Since we want to calculate the mean of the given list so we will use `statistics.mean(list)`

. `list`

is the list of numbers. This function will return the mean (average) of the given list.

The basis example to use this `statistics.mean()`

method is shown below,

`import statistics list = [1, 2, 3, 4, 5, 6] mean = statistics.mean(list) print(mean) `

Output:

`3.5 `

`sum()/len()`

Using `statistics`

library for calculating the average of a list is not the only option. The average of the list can be calculated by simply dividing the sum of elements by them number of elements.

`sum(list)`

obtains the sum of the given list, and `len(list)`

returns the length of the list.

`data = [1, 2, 3, 4, 5, 6] mean = sum(data)/len(data) print(mean) `

Output:

`3.5 `

`numpy.mean()`

We can also use the to get the average of a list in Python. The average is taken over the flattened array by default, otherwise over the specified axis.

However, you need to first install the `NumPy`

module before using it.

The example code to get the average of a list using `numpy.mean()`

is as follows.

`import numpy data = [1, 2, 3, 4, 5, 6] mean = numpy.mean(data) print(mean) `

Output:

`3.5 `

`sum()/float(len())`

in Python 2If your Python version is 2.x, then you are not able to use the `statistics`

module and have to use the simple mathematical formula to calculate the average of a given list.

For Python 2 you will need to convert `len`

to a float to get float division. The code will look like this:

`data = [1, 2, 3, 4, 5, 6] mean = sum(data)/float(len(data)) print(mean) `

Output:

`3.5 `

If you do not convert `len`

to float, you will not get the floating number but an integer, as shown below.

`data = [1, 2, 3, 4, 5, 6] mean = sum(data)/len(data) print(mean) `

Output:

`3 `