Overview
Count how many times each value appears by iterating and tallying in a dictionary.
Analogy
Counting votes: each ballot increments the candidate's count by 1.
Step-by-step
- Create an empty dict counts = {}.
- For each item: counts[item] = counts.get(item, 0) + 1.
- Or use collections.Counter(iterable) directly.
Visual
['a','b','a','c','b','a'] → {'a':3,'b':2,'c':1}
Common mistakes
- KeyError when accessing a missing key — use .get() or defaultdict.
- Counter.most_common() returns sorted list — don't iterate the Counter for sorted output.
Practice questions
- Count word frequencies in a sentence.
- Find the most common element without Counter.
Space
O(k) where k = distinct values