statistics module in python 3 | statistical functions in python 3

Preview




statistics module in Python 3

Python has a predefined module statistics that provides statistical functions.

To use statistical functions in our Python program, we first need to import module statistics by using import statement as:

import statistics

Most commonly used  functions of this module  are:

  • mean()
  • mode()
  • median()

i. mean()

This function is used to find average value from a sequence of values. It can be used to find mean of values from list, tuple as well as dictionary.

** Commands tried using spyder

In [1]: import statistics
In [2]: list1=[1,3,4,5,4]
In[3]: print(statistics.mean(list1))
3.4#Average of values contained in list1=[1,3,4,5,4]In [4]: t1=(1,3,4,5,4)
In[5]: print(statistics.mean(t1))
3.4#Average of values contained in tuple t1=[1,3,4,5,4]

In [6]: d1={1:’a’,3:’b’,5:’c’}
In[7]: print(statistics.mean(d1))
3

#Average of values contained in dictionary d1=[1,3,4,5,4]

ii. mode()

This function is used to find value having occurrence for largest number of times. It can be used to find mode of values from list and tuple.

In [1]: import statistics
In [2]: list1=[1,3,4,5,4]
In[3]: print(statistics.mode(list1))
4 #4 occurs maximum number of times in the list list1.In [4]: t1=(1,3,4,5,4)
In[5]: print(statistics.mean(t1))
4#4 occurs maximum number of times in the tuple t1.

iii. median()

This function is used to find median value from a sequence of values. It can be used to find median of values from list, tuple as well as dictionary. When the number of data items is odd, the middle value is returned.

When the number of values are even, the median is calculated by taking the average of the two middle values.

In [1]: import statistics
In [2]: list1=[1,3,4,5,4]
In[3]: print(statistics.median(list1))
4#4 appears in the middle of list.In [4]: t1=(1,3,4,5)
In[5]: print(statistics.mean(t1))
3.5#Average of tuple values at positions 2 and 3 i.e. 3 and 4.Average of 3 and 4 is 3.5

In [6]: d1={1:’a’,3:’b’,5:’c’}
In[7]: print(statistics.mean(d1))
3

#3  is the middle element of dictionary.




Lesson tags: mean of values in python, median of values in python, mode of values in python, statistics module in python 3
Back to: Python Programming Tutorial