Counter
Class from collections
in PythonThe Counter
class from the collections
module is a specialized dictionary used for counting hashable objects (e.g., numbers, strings, tuples). It simplifies counting elements in lists, strings, and other iterables.
from collections import Counter
# Example list
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
# Create a Counter
counter = Counter(numbers)
print(counter)
# Output: Counter({4: 4, 3: 3, 2: 2, 1: 1})
* Counts occurrences of each element.
text = "banana"
char_count = Counter(text)
print(char_count)
# Output: Counter({'a': 3, 'n': 2, 'b': 1})
print(counter[3]) # Output: 3 (count of 3 in list)
print(counter[5]) # Output: 0 (5 is not in the list)
* Returns 0
for missing elements (instead of KeyError).
top_counts = counter.most_common(2) # Get top 2 most common elements
print(top_counts)
# Output: [(4, 4), (3, 3)]
* Great for finding the most frequent items.
Counters support addition, subtraction, intersection, and union.
c1 = Counter("apple")
c2 = Counter("pear")
# Add counts
print(c1 + c2)
# Output: Counter({'p': 3, 'a': 2, 'e': 2, 'l': 1, 'r': 1})
# Subtract counts
print(c1 - c2)
# Output: Counter({'l': 1})
* Useful for bag-of-words models in NLP!
elements = list(counter.elements())
print(elements)
# Output: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
* Expands the counts back into a list.
Counter
?* Counting words in a document (NLP).
* Finding the most common elements in a dataset.
* Histogram-like frequency analysis.