Skip to content
IT Vizag
← Advanced Python Features

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

collections and itertools

Lesson 8 of 10 · 2 min read

Counter, defaultdict, deque and the itertools toolkit.

🎬 Video version coming soon — read it now

Two standard-library modules solve many everyday problems in a line or two. Knowing them separates intermediate Python from advanced.

Counter: counting made easy

🔒 Code example: sign up free (above) to unlock it.

That replaces the counts.get(w, 0) + 1 loop you wrote by hand in Lists, Dicts & Data.

defaultdict: no more "if key not in dict"

🔒 Code example: sign up free (above) to unlock it.

A missing key is created automatically using the factory you gave (list, int, set...).

deque: a fast queue

🔒 Code example: sign up free (above) to unlock it.

namedtuple: lightweight records

🔒 Code example: sign up free (above) to unlock it.

(For most new code, a frozen dataclass is clearer.)

itertools: building blocks for loops

🔒 Code example: sign up free (above) to unlock it.

groupby: group sorted data

🔒 Code example: sign up free (above) to unlock it.

groupby only groups neighbouring items, so sort by the same key first. Forgetting that is a classic bug.

Also worth knowing

  • collections.ChainMap: look up keys across several dictionaries, such as settings with defaults
  • itertools.batched (Python 3.12+): split an iterable into chunks of n, which is handy for sending items to an API in batches
Tip: When you write a loop that counts, groups, pairs or chunks things, check collections and itertools first. There's often a one-line tool for it.

In one line

Counter counts, defaultdict groups, deque queues, and itertools chains, slices, combines and groups, all built in.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend