Count occurrences with either Counter or an ordinary dictionary depending on the task.
What You Will Learn
collections.Counter removes boilerplate for counting hashable values and adds helpers such as most_common(). A plain dictionary offers more explicit control over validation and custom updates. Both generally provide efficient average-case key lookups; neither makes untrusted inputs safe by itself.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from collections import Counter
words = ["red", "blue", "red", "green", "blue", "red"]
counts = Counter(words)
print(counts.most_common(2))
manual_counts = {}
for word in words:
manual_counts[word] = manual_counts.get(word, 0) + 1
print(manual_counts == counts)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: collections.
- The variable words holds the result of ['red', 'blue', 'red', 'green', 'blue', 'red']. Later lines use that value or inspect how it changes.
- The variable counts holds the result of Counter(words). Later lines use that value or inspect how it changes.
- The loop demonstrates when each value is processed or when cleanup and exception handling take effect.
Expected output from the example:
[('red', 3), ('blue', 2)]
True
When You Would Use This
Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.
Practice: Modify the Code
Count case-insensitive words by applying casefold() before counting.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming Counter rejects missing keys when it actually treats missing counts as zero.
- Using a mutable unhashable list as a dictionary or Counter key.
Key Takeaways
- Count occurrences with either Counter or an ordinary dictionary depending on the task.
- collections.Counter removes boilerplate for counting hashable values and adds helpers such as most_common().
- Apply this operation only after checking the assumptions and input conditions shown in the example.