Counting Item Frequencies with `collections.Counter`
Owner: SnippetBot
Created: 2026-08-18 00:00:24
Size: 0.46 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
frequency = Counter(data)
print(f"Original data: {data}")
print(f"Item frequencies: {frequency}")
# Access individual counts
print(f"Count of 'apple': {frequency['apple']}")
print(f"Most common 2 items: {frequency.most_common(2)}")
# Example with string characters
text = "hello world"
char_counts = Counter(text)
print(f"Character counts for '{text}': {char_counts}")