Python collections Exercises: Count, Group, and Queue
The collections module is a set of small tools that remove boilerplate. Instead of writing a counting loop, a missing-key check, or a manual queue, you pick a container whose behavior already matches the problem.
Count first, then decide
Counter turns an iterable into counts. It is a dictionary subclass, so missing keys read as zero and you can still use normal mapping methods. most_common is useful for a quick ranking, while direct indexing answers a single lookup.
from collections import Counter
votes = ["yes", "no", "yes", "yes"]
counts = Counter(votes)
print(counts["yes"])
print(counts.most_common(1))Count once, query many times
Give missing keys a sensible default
defaultdict calls a factory when a key is absent. With list, you can append immediately instead of checking whether the key exists. The factory must be callable, and the default is created only when that key is accessed.
from collections import defaultdict
groups = defaultdict(list)
for word in ["ant", "ape", "bee"]:
groups[word[0]].append(word)
print(dict(groups))Group without key checks
Use deque when both ends matter
A list is efficient at the right end and expensive at the left. deque supports fast append and pop on both sides. Use appendleft and popleft for a queue, or rotate when you need to move items around a circle.
from collections import deque
queue = deque(["a", "b"])
queue.append("c")
queue.popleft()
print(list(queue))Fast operations at both ends
Combine counts with arithmetic
Counter objects support addition and subtraction of counts. This is handy for comparing two bags of items, but negative results are dropped by subtraction. Use update to add counts from another iterable or mapping.
from collections import Counter
first = Counter("aab")
second = Counter("abb")
print(first + second)
print(first - second)Counts are values you can combine
Choose by the operation you need
Pick a container from the operation that will dominate: counting, grouping, or end access. A plain dict is still the right choice when defaults and counting are irrelevant. Readability comes from matching the tool to the task, not from using every container in one file.
from collections import Counter, deque
print(Counter("aba").most_common(1))
print(deque([1, 2, 3]).popleft())Match the container to the job
Your practice checklist
- Use Counter when you need frequencies, not just membership.
- Use defaultdict(list) to group values without pre-creating lists.
- Use deque for queues and fast left-end operations.
- Remember that Counter subtraction drops non-positive counts.
- Choose a container based on the operation you repeat most.
Common questions
Is Counter a dict?
Yes. Counter is a dict subclass, with missing keys treated as zero for lookups.
When should I use defaultdict instead of dict.get?
Use defaultdict when the same missing-key default appears throughout a loop. For one or two lookups, dict.get is often clearer.
Can deque be indexed?
Yes, indexing works, but it is not the main reason to use deque. Choose deque when adding or removing at both ends is the common operation.
Practice collections
12 questions on Counter, defaultdict, deque, grouping, and container choice.
Keep reading: