There are often cases where you'll want to count the frequency of elements in a list. Consider a problem where you need to find the frequency of words in a document.

We can use this short paragraph as an example.

paragraph = "I am. And this my trusty servant Patsy. We have ridden the length and breadth of the land in search of knights who will join me in my court of Camelot. I must speak with your lord and master."

First we want to make sure this document only contains words and spaces (no punctuation).

paragraph = re.sub(r'[^\w\s]', '', paragraph)

And then we want to split the paragraph by whitespace and return a list.

words = re.split(r'\s+', paragraph)

And now with our list of words, we can use Counter to give us our word frequencies.

from collections import Counter counter = Counter(words)

From this we can get the 5 most commonly used words:

counter.most_common(5) > [('of', 3), ('and', 2), ('in', 2), ('I', 2), ('the', 2)]

Or we can return the frequency of a desired word.