Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Word Frequency

Medium · 50 XP

Print the three most common words in the starter text, one per line as word count.

Target output
the 4
and 3
fox 2
Blank · autosaved
PYword-frequency.py
Run your code to check it…
Guide

How to approach Word Frequency

Frequency counting is a dictionary that maps each word to how many times it has been seen. You can build one by hand with counts[w] = counts.get(w, 0) + 1, but collections.Counter exists precisely for this and does it in one call.

Counter(text.split()).most_common(3) returns the three highest counts as (word, count) pairs, largest first. Unpack each pair in the loop and print them with a space between, which is what print(word, count) does by default.

Worked through on this data

  1. Splitting on whitespace gives 14 words. "the" appears 4 times and "and" 3 times.
  2. "fox" appears twice. Every other word (quick, lazy, dog, sleepy, cat) appears once.
  3. The top three are the 4, and 3, fox 2: one pair per line, matching the target.

Common mistakes

  • Real text has capitals and punctuation, so "The" and "fox." would count as different words. Normalise with .lower() and strip punctuation before counting.
  • Sorting a dict by value by hand and forgetting reverse=True gives the three least common words.
  • text.split(" ") treats two spaces in a row as an empty word; plain text.split() does not.

Time and space

Counting is one pass, O(n) in the number of words. most_common(k) uses a heap, so it costs O(m log k) over m distinct words rather than a full sort.

Where this shows up

Word counts are the start of search indexing, log analysis (which error message is most common?) and every "top 10" report a product team asks for.

Take it further

Read a paragraph of real text, lowercase it, strip punctuation with str.maketrans, and ignore a small set of stop words such as "the" and "and" before counting.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path