PYTHON
Counting Frequencies with Python's collections.Counter
Discover how to quickly count the occurrences of items in a list or string using Python's `collections.Counter`, ideal for analytics or tag frequency in web applications.
from collections import Counter
tags = ["python", "django", "javascript", "python", "flask", "django", "python"]
user_actions = ["login", "logout", "login", "view_profile", "login", "view_post"]
# Count tag frequencies
tag_counts = Counter(tags)
print(f"Tag Counts: {tag_counts}")
# Count user action frequencies
action_counts = Counter(user_actions)
print(f"Action Counts: {action_counts}")
# Access most common items
print(f"Most common tags: {tag_counts.most_common(2)}")
How it works: `Counter` is a subclass of `dict` that helps count hashable objects. It's incredibly efficient for tallying occurrences in lists, tuples, or strings. It can be used directly with an iterable, and provides useful methods like `most_common()` to get the n most frequent items, making it perfect for generating statistics or analyzing user behavior in web applications.