Counter โ Fast Counting
from collections import Counter
words = "the quick brown fox jumps over the lazy dog the the".split()
print(Counter(words).most_common(3))
# [('the', 4), ('quick', 1), ('brown', 1)]
defaultdict โ No KeyError
from collections import defaultdict
groups = defaultdict(list)
for word in ["apple", "ant", "bird", "bee"]:
groups[word[0]].append(word)
# {'a': ['apple','ant'], 'b': ['bird','bee']}
deque โ Double-Ended Queue
from collections import deque dq = deque([1, 2, 3]) dq.appendleft(0) # [0,1,2,3] dq.append(4) # [0,1,2,3,4] dq.popleft() # O(1) โ list.pop(0) is O(n)
When to Reach For These
- Counting anything โ
Counter. - Grouping by key โ
defaultdict(list). - Queue/BFS โ
deque.
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ