Skip to content

The collections Module

Beginning of the lesson

The collections Module

Purpose-built containers that make everyday counting, grouping and queueing trivial

Big Idea: Python's built-in dict and list handle almost everything, but three specialised containers from the standard-library collections module remove boilerplate you would otherwise write by hand every day. Counter tallies things, defaultdict supplies a value for missing keys automatically, and deque adds and removes from both ends in constant time. None of them is exotic; each is just the plain data structure you already know with the tedious parts done for you.
By the end you will be able to:
  • tally items with Counter and read the most common ones,
  • group and accumulate values with defaultdict without KeyError,
  • build fast queues and stacks with deque,
  • explain why deque.popleft() beats list.pop(0),
  • pick the right container for a given task.

1. Why reach past plain dict and list?

You already build dictionaries and lists comfortably. But some patterns keep repeating: counting how many times each value appears, collecting items into groups keyed by some property, or treating a list as a queue where you remove from the front. Each of these has a clean solution in raw Python, and each also has an annoying wrinkle.

Counting by hand means checking whether a key exists before you increment it:

counts = {}
for word in words:
    if word not in counts:
        counts[word] = 0
    counts[word] += 1

Grouping by hand has the same shape — you must create the empty list the first time you see a key. And using a plain list as a queue is quietly slow: list.pop(0) shifts every remaining element one slot to the left, so removing from the front of an n-element list costs O(n) each time.

The collections module ships three containers that erase exactly these wrinkles. You import them once and the boilerplate disappears:

from collections import Counter, defaultdict, deque

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers