Reading Time: 1 minutes
Fetching Most Frequent Elements from an Iterable Object in Python
Fetching Most Frequent Elements from an Iterable Object: Write a Python program to retrieve most frequent elements from an iterable object.
Fetching Most Frequent Elements from an Iterable Object
import collections words = [ '!', '@', '#', '$', '%', '@', '#', '$', '%', '#', '$', '%', '$', '%', '%', ] characterCounts = collections.Counter(words) threeMostFrequentCharacters = characterCounts.most_common(3) print(threeMostFrequentCharacters) # [('%', 5), ('$', 4), ('#', 3)]
The Counter class of builtin module collections creates a dictionary of all elements of a given iterable object, along with corresponding number of occurrences. It provides a few useful methods, one of which is most_common(). This method takes an integer input, say n, and provides a list of tuples of n most common elements with their corresponding number of occurrences.