Free Online Code Editor
Count occurrences with Counter.
from collections import Counter
# Count list items
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(numbers)
print(f"Counter: {counter}")
# Most common
print(f"\nMost common: {counter.most_common(3)}")
# Count string
text = "hello world"
char_count = Counter(text)
print(f"\nChar count: {char_count}")
print(f"Most common chars: {char_count.most_common(5)}")
# Update counter
counter.update([5, 5, 5])
print(f"\nAfter update: {counter}")
# Access counts
print(f"\nCount of 4: {counter[4]}")
print(f"Count of 99: {counter[99]}") # Returns 0
# Counter operations
c1 = Counter("abracadabra")
c2 = Counter("alacazam")
print(f"\nAddition: {c1 + c2}")
print(f"Subtraction: {c1 - c2}")
print(f"Intersection: {c1 & c2}")
print(f"Union: {c1 | c2}")
# Practical example
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_freq = Counter(words)
print(f"\nWord frequencies: {word_freq}")
print(f"Top 2: {word_freq.most_common(2)}")Counter counts occurrences of elements. Use most_common(n) to get top n items. Supports addition, subtraction, intersection, union.