AppDividend
Latest Code Tutorials

Python Mode Function Example | Python Statistics Tutorial

0

In this example, we will see Python Mode Function Example | Python Statistics Tutorial. Python is a very robust language when it comes to statistics and working with a set of broad range of values. Python statistics module has a considerable number of functions to work with very large data-sets. The mode() function is one of such methods. A mode is the only function in statistics which also applies to nominal (non-numeric) data. The mode is used to locate the central tendency of numeric or nominal data. A mode is a value at which the data is most likely to be sampled.

Python Mode Function Example

The mode is the statistical term that refers to the most frequently occurring number found in a set of numbers. The mode is detected by collecting and organizing data to count the frequency of each result.

In Python, we use the Statistics module to calculate the mode. See the following example.

# app.py

import statistics

listA = [19, 21, 46, 19, 18, 19]
print(statistics.mode(listA))

In the above code, number 19 is frequently appearing. So that is our mode. See the below output.

 

Python Mode Function Example

Now, let’s see the unique item list.

# app.py

import statistics

listUnique = [19, 21, 18, 30, 46]
print(statistics.mode(listUnique))

The above list has unique elements inside the list. So mode does not work here. Instead, it will give us an error. See the below output.

 

Python Statistics Tutorial

Calculate Mode of Tuple in Python

Let’s define a tuple and calculate the mode of Tuple.

# app.py

import statistics

data = (21, 19, 18, 46, 30, 18, 19, 21, 18)
print(statistics.mode(data))

Let’s see the output.

 

Calculate Mode of Tuple in Python

More Examples

Let’s add more examples to the app.py file.

# app.py

import statistics
from fractions import Fraction as fr

data1 = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4) 
print(statistics.mode(data1))

data2 = (2.1, 1.9, 2.1, 1.8, 2.9) 
print(statistics.mode(data2))

data3 = (fr(19, 21), fr(18, 21), fr(19, 21), fr(21, 46)) 
print(statistics.mode(data3))
  
data4 = (-21, -22, -21, -29, -18, -19) 
print(statistics.mode(data4))
  
data5 = ('Emily', 'Matt', 'Ross', 'Rachel', 'Monica', 'Chandler', 'Rachel') 
print(statistics.mode(data5))

See the output below.

 

Python Mode Function Example | Python Statistics Tutorial From Scratch

It will work with Strings as well, as we have defined the list of Strings in the last example.

Finally, Python Mode Function Example | Python Statistics Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.