Back
+15 XP
Concept

`collections.Counter`: Instant Frequency Maps

`Counter(seq)` counts how many times each item appears in an iterable and provides `.most_common(n)` for instant top-ranking analytics 📊.

python
from collections import Counter

votes = ["yes", "no", "yes", "yes", "abstain"]
counts = Counter(votes)
print(counts["yes"])          # 3 🗳️
print(counts.most_common(1))  # [('yes', 3)] 🏆

# 27. `collections.Counter`: Instant Frequency Maps `Counter(seq)` counts how many times each item appears in an iterable and provides `.most_common(n)` for instant top-ranking analytics 📊: ```python from collections import Counter votes = ["yes", "no", "yes", "yes", "abstain"] counts = Counter(votes) print(counts["yes"]) # 3 🗳️ print(counts.most_common(1)) # [('yes', 3)] 🏆 ``` Never write manual frequency tracking loops using vanilla dictionaries. `Counter` is heavily optimized in C and supports arithmetic operations like subtracting one inventory counter from another! ⚡ --- ### Question What does `Counter` return if you query an item that was never seen? 🔍 - [ ] a. `0` (never raises KeyError, perfectly behaving like a zero frequency) - [ ] b. `None` - [ ] c. Throws a `CounterMissingError` 💥 - [ ] d. Returns `-1` to mock your data queries 🤦‍♂️ --- ### Challenge Count items in `words = ["apple", "orange", "apple"]` with `Counter`. Print `counts["apple"]`. 🎯 <details> <summary>Solution</summary> ```python from collections import Counter words = ["apple", "orange", "apple"] counts = Counter(words) print(counts["apple"]) ``` </details>

Checkpoint

What does `Counter` return if you query an item that was never seen? 🔍

Practice

Count items in `words = ["apple", "orange", "apple"]` with `Counter`. Print `counts["apple"]`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks