How to Use the Counter Class for Counting Elements in a List

from collections import Counter

word_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(word_list)
print(f"Word List: {word_list}\nWord Counts: {word_counts}")

Output:

Word List: [‘apple’, ‘banana’, ‘apple’, ‘orange’, ‘banana’, ‘apple’]
Word Counts: Counter({‘apple’: 3, ‘banana’: 2, ‘orange’: 1})

Leave a Comment

Your email address will not be published.