Count hashable items and query their frequencies.
What You Will Learn
Counter is a dictionary subclass mapping elements to counts. Missing keys read as zero, but Counter can store negative or zero counts after updates.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from collections import Counter
colors = Counter(['blue', 'red', 'blue', 'green'])
print(colors['blue'])
print(colors['missing'])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: collections.
- The variable colors holds the result of Counter(['blue', 'red', 'blue', 'green']). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
2
0
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from collections import Counter
print(Counter("banana").most_common(2))
Expected output:
[('a', 3), ('n', 2)]
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 words in a sentence after normalizing case.
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 all stored counts must be positive or that missing keys cause KeyError.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Count hashable items and query their frequencies.
- Counter is a dictionary subclass mapping elements to counts.
- Apply this operation only after checking the assumptions and input conditions shown in the example.