most_common method of counter class

most_common() returns a list of most commonly occurring n elements in a counter object and their counts.

Counter Updated 23 Mar 2017 1 min read

Method Name

most_common

Method Signature

most_common(n)

Method Overview

  • most_common() returns a list of top 'n' elements from most common to least common, as specified the parameter 'n'.

  • The list consists of tuples and each tuple contains the element and the element count

  • If the parameter 'n' is not specified or None is passed as the parameter most_common() returns a list of all elements and their counts

  • The ordering of elements occurring with the same count is arbitrary.

Example

python
import collections

counterObject = collections.Counter()

# Tea types vs number of cups

counterObject["Green tea"]  = 10

counterObject["Yellow tea"] = 8

counterObject["White tea"]  = 10

counterObject["Oolong tea"] = 5

counterObject["Black tea"]  = 15

# most common tea requirement - top 1

print("Topmost tea requirement:")

print(counterObject.most_common(1))

print("Tea requirement - top 2")

print(counterObject.most_common(2))

print("Tea type vs requirement:")

print(counterObject.most_common())

Output

Output
Topmost tea requirement:

[('Black tea', 15)]

Tea requirement - top 2

[('Black tea', 15), ('Green tea', 10)]

Tea type vs requirement:

[('Black tea', 15), ('Green tea', 10), ('White tea', 10), ('Yellow tea', 8), ('Oolong tea', 5)]