Categories
Python Answers

How to count frequency of words in a list and sort by frequency with Python?

Spread the love

Sometimes, we want to count frequency of words in a list and sort by frequency with Python.

In this article, we’ll look at how to count frequency of words in a list and sort by frequency with Python.

How to count frequency of words in a list and sort by frequency with Python?

To count frequency of words in a list and sort by frequency with Python, we can use the Counter class.

For instance, we write

from collections import Counter
list1 = ['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)

to create a Counter object with list1.

Then we get a Counter object that has the key being the item in list1 and the value being the frequency of each item.

The items are sorted by frequency in counts.

Conclusion

To count frequency of words in a list and sort by frequency with Python, we can use the Counter class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *