Stop 08 · Intermediate PythonTopics · 6/10

The collections Module

Part of the Python Roadmap

In short

Counting things, grouping things and building queues come up in almost every program. The collections module has a ready-made, well-tested container for each of these jobs.

collections adds specialised containers: Counter counts items, defaultdict supplies default values for missing keys, deque is a fast double-ended queue, and namedtuple gives tuples readable field names.

The jaadu works in a small neighbourhood shop, clicking a hand tally counter while sorting items into ready-made bins.

Think of it like this

Special shelves in a kirana store

A regular shelf can hold anything, but a good kirana store also has a tally counter at the billing desk (Counter), bins that come with a label already stuck on (defaultdict), and a counter where people can join or leave from both ends (deque). collections gives you those special shelves.

Watch it happen

deque as a recent-searches list (maxlen=3)

enqueue(laptop)
laptop

Front of the queue is coloured

1/5append('laptop'). The deque has one search.

The big ideas

What you need to know

Counter

Counter(words) counts everything in one line. .most_common(3) gives the top three.

defaultdict

defaultdict(list) creates an empty list for any new key, so grouping needs no 'if key not in d' checks.

deque

Fast appends and pops at both ends. Perfect for queues, and maxlen keeps only the latest N items.

namedtuple

A tuple with named fields: p.lat instead of p[0], still lightweight and immutable.

See it in code

Walk through the code

python
1from collections import Counter, defaultdict, deque, namedtuple2 3votes = ["Mango", "Chikoo", "Mango", "Guava", "Mango", "Guava"]4tally = Counter(votes)5print(tally.most_common(2))    # [('Mango', 3), ('Guava', 2)]6print(tally["Lychee"])         # 0, no KeyError7 8orders = [("Pune", 450), ("Agra", 300), ("Pune", 800)]9by_city: defaultdict[str, list[int]] = defaultdict(list)10for city, amount in orders:11    by_city[city].append(amount)12print(dict(by_city))           # {'Pune': [450, 800], 'Agra': [300]}13 14queue = deque(["Token 1", "Token 2"])15queue.append("Token 3")        # join at the back16print(queue.popleft())         # Token 1 served first17recent = deque(maxlen=3)18for item in ["laptop", "phone", "earbuds", "watch"]:19    recent.append(item)20print(list(recent))            # ['phone', 'earbuds', 'watch']21 22City = namedtuple("City", ["name", "lat", "lon"])23goa = City("Panaji", 15.49, 73.83)24print(goa.name, goa.lat)       # Panaji 15.49

1/5Counter counts each item. Missing items return 0 instead of raising KeyError.

Counting votes, grouping orders by city, a fair queue, a recent-items list and named coordinates.

Save yourself the pain

Common mistakes

Oops

Using list.pop(0) for a queue with thousands of items.

Do this instead

pop(0) shifts every remaining item. Use deque.popleft(), which is fast.

Oops

Writing if key not in d: d[key] = [] before every append.

Do this instead

Use defaultdict(list) or d.setdefault(key, []).append(x).

Your mission

Word statistics

~20 min

Quick check

Counter(['a', 'b', 'a'])['z'] returns:

Go deeper

  1. 1Count the most common words in a paragraph with Counter.most_common().
  2. 2Group students by city with defaultdict(list).
  3. 3Keep only the last five items with deque(maxlen=5).

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge