liveBook · Manning

Counter.most_common

As explained in Python Workout, Second Edition

Counter.most_common is a Counter method that returns elements and their counts ordered from most common to least common.

Use Counter.most_common to retrieve counted elements in descending frequency order. Counter accepts a sequence such as a word and produces count data. section 4.15 section 4.22

Find a word’s most repeated letter count

Counter(word).most_common(1) returns a one-element list containing a (letter, count) tuple. Indexing [0][1] extracts its count: def most_repeating_letter_count(word): return Counter(word).most_common(1)[0][1]. Use that function as max’s key when selecting the word with the strongest repetition. section 4.15

>>> Counter('abcabcabbbc').most_common(1)     #1
[('b', 5)]

Compare unrestricted results with most_common(1), which limits the output to the highest-count item. section 4.15

How Python Workout, Second Edition covers it

How deep it goes
Explains descending tuple results, the n argument, and indexing, but stops short of implementation internals.
Examples
Demonstrates character counts and selecting the word with the most repeated letter.
What it assumes
Assumes familiarity with sequences, tuples, indexing, dictionaries, and functions passed as key arguments.
What you can do after
Apply it via collections.Counter to retrieve the highest count or a ranked subset of counted items.
How it connects
Connects Counter with dictionaries, sequences, max, and key functions.

Also explained in

Compare how 2 books explain Counter.most_common →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.