Content · Programming · Python

Python Counter.most_common() Method: Usage and Examples

Retrieve frequent elements and their counts.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Retrieve frequent elements and their counts.

What You Will Learn


most_common(n) yields the n highest-count pairs as a list. Tied counts keep encounter order in modern Python implementations when sorting stable count totals.

Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from collections import Counter
frequencies = Counter('abbccc')
print(frequencies.most_common(2))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: collections.
  • The variable frequencies holds the result of Counter('abbccc'). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression frequencies.most_common(2) prints [('c', 3), ('b', 2)]. Compare that result with the rule above before you change the argument.

Expected output from the example:

[('c', 3), ('b', 2)]

Another Example: Compare the Results


Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.

from collections import Counter
print(Counter("abracadabra").most_common(2))

Expected output:

[('a', 5), ('b', 2)]

When You Would Use This


A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.

Practice: Modify the Code


Report the top three categories in a transaction list.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Mistaking most_common(2) for the two least frequent items.
  • Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.

Key Takeaways


  • Retrieve frequent elements and their counts.
  • most_common(n) yields the n highest-count pairs as a list.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.