The collections Module
Counter counts items, defaultdict creates missing keys automatically and deque is a fast queue that you can add to or remove from either end. They save a lot of manual code.
Example
from collections import Counter, defaultdict, deque
words = "to be or not to be".split()
print(Counter(words).most_common(2))
groups = defaultdict(list)
for w in words:
groups[len(w)].append(w)
print(dict(groups))
q = deque([1, 2, 3])
q.append(4)
print(q.popleft(), list(q))Result
[('to', 2), ('be', 2)]
{2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']}
1 [2, 3, 4]Exercise
Count the items.
from collections import Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.