Counter

Counting occurrences

Interview Relevant: Very common in interviews

Counter

Specialized dictionary for counting.

Code Examples

Counter for frequency counting.

python
1from collections import Counter
2
3# Count elements
4c = Counter("abracadabra")
5# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
6
7# From list
8c = Counter([1, 2, 2, 3, 3, 3])
9
10# Most common
11c.most_common(2)  # [(3, 3), (2, 2)]
12
13# Access counts
14c[3]    # 3
15c[99]   # 0 (missing keys return 0)
16
17# Arithmetic
18c1 = Counter("aab")
19c2 = Counter("abc")
20c1 + c2  # Counter({'a': 3, 'b': 2, 'c': 1})
21c1 - c2  # Counter({'a': 1})
22
23# Elements (repeat by count)
24list(c.elements())  # [1, 2, 2, 3, 3, 3]
25
26# Update
27c.update("aaa")  # Add more counts
28
29# Check anagram
30Counter("listen") == Counter("silent")  # True

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In