# Element with largest frequency in list in Python

A lot of statistical data analysis tries to find the values which have maximum frequency in a given list of values. Python provides multiple approaches using which we can find such value form a given list. Below are the approaches.

## Using Counter

The Counter function from collections module has a options which can directly find the most common element in a given list. We have the most_common function to which we pass a parameter 1 for only one element with highest frequency and pass 2 if we need two elements which have highest frequency.

## Example

Live Demo

from collections import Counter

# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]

print("Given list : ",listA)

# Adding another element for each element
Newlist1 = Counter(listA).most_common(1)
Newlist2 = Counter(listA).most_common(2)

# Results
print("New list after duplication: ",Newlist1)
print("New list after duplication: ",Newlist2)

## Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 'Mon', 9, 3, 3]
New list after duplication: [('Mon', 2)]
New list after duplication: [('Mon', 2), (3, 2)]

## Using mode

The mode is a statistical function available in the statistics module of python. It will output the element with highest frequency. If there are multiple such elements then the element which is encountered first with highest frequency will be the output.

## Example

from statistics import mode

# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
listB = [3,3,'Mon', 'Tue','Mon', 9]
print("Given listA : ",listA)
print("Given listB : ",listB)

# Adding another element for each element
Newlist1 = mode(listA)
Newlist2 = mode(listB)

# Results
print("New listA after duplication: ",Newlist1)
print("New listB after duplication: ",Newlist2)

## Output

Running the above code gives us the following result −

Given listA : ['Mon', 'Tue', 'Mon', 9, 3, 3]
Given listB : [3, 3, 'Mon', 'Tue', 'Mon', 9]
New listA after duplication: Mon
New listB after duplication: 3

Advertisements