PYTHON
Efficient Frequency Counting with `collections.Counter`
Learn to efficiently count item frequencies in a list or string using Python's `collections.Counter` for streamlined data analysis tasks.
from collections import Counter
# Count word frequencies in a sentence
sentence = "this is a test sentence and this sentence is a test"
words = sentence.split()
word_counts = Counter(words)
print(f"Word frequencies: {word_counts}")
print(f"Most common word: {word_counts.most_common(1)}")
# Count character frequencies in a string
text = "hello world"
char_counts = Counter(text)
print(f"Character frequencies: {char_counts}")
# Combine counters
another_sentence = "this is another test"
another_words = another_sentence.split()
another_word_counts = Counter(another_words)
total_word_counts = word_counts + another_word_counts
print(f"Combined word frequencies: {total_word_counts}")
How it works: The `collections.Counter` class is a subclass of `dict` designed for counting hashable objects. It's incredibly useful for frequency analysis. You initialize it with an iterable (like a list or string), and it automatically tallies the occurrences of each element. It provides methods like `most_common()` to easily retrieve the elements with the highest frequencies and supports arithmetic operations for combining counts.