Back to Home 24 lessons Pyodide ready

Python Collections & Itertools
Specialized Data Structures & Iterators

Master Python's collections and itertools modules: Counter, defaultdict, deque, namedtuple, chain, product, combinations, and more. 24 interactive lessons with runnable code β€” crafted by @PoeticGlenn.

What you will learn

Everything about Python's two most powerful standard-library modules. The collections module gives you specialized data structures that replace verbose boilerplate: Counter for counting, defaultdict for auto-initializing dicts, deque for fast queues, namedtuple for lightweight records, and OrderedDict for explicit ordering. The itertools module gives you composable iterator building blocks: chain, product, combinations, permutations, groupby, accumulate, and more. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.

Why These Two Modules Are Python's Best-Kept Secrets

The collections and itertools modules are part of Python's standard library and are used heavily by experienced developers. They replace dozens of lines of boilerplate with single, expressive calls. Counting items? That's Counter. Grouping data? That's defaultdict(list). Flattening lists? That's itertools.chain.from_iterable(). Generating test cases? That's itertools.product(). This curriculum, designed by @PoeticGlenn, teaches you to see the standard library as a toolbox β€” and to reach for the right tool every time.

collections

Specialized data structures: Counter, defaultdict, deque, namedtuple.

itertools

Composable iterators: chain, product, groupby, islice.

Concise & Fast

Less code, fewer bugs, C-level performance β€” all from the standard library.

"The standard library is a gift. Collections and itertools are the gift-wrapped ones." β€” @PoeticGlenn 🐍

Write Less Code, Solve More Problems

Every Python developer eventually hits a limit with plain dicts, lists, and loops. collections and itertools are how you break past that limit. They turn complex logic into readable one-liners, and they're battle-tested by millions of projects. This curriculum, curated by @PoeticGlenn, walks you through the tools you'll actually use β€” not every esoteric corner, but the high-value patterns that make Python code feel like poetry.

πŸ“Š Counting & Grouping

Counter and defaultdict replace manual tallying loops.

πŸ”„ Queues & Stacks

deque gives O(1) append/pop on both ends β€” faster than list for many uses.

🎲 Combinatorics

product, combinations, permutations β€” instant test cases.

πŸ”— Composable Iteration

Chain, slice, group, accumulate β€” build complex pipelines with simple building blocks.

@PoeticGlenn says: "When you find yourself writing a loop that counts or groups, stop β€” the standard library already did it."

The Standard Library Is Your Superpower

Python's "batteries included" philosophy is one of its greatest strengths. The collections and itertools modules are the purest expression of that philosophy β€” they give you the tools to solve a huge range of problems without installing anything. Libraries like Django, pandas, and NumPy all rely on these modules internally. Learning them, as taught by @PoeticGlenn, makes you faster in every Python project you'll ever work on.

Always Available

No install, no imports to worry about β€” part of every Python 3 install.

Battle-Tested

Used by every major Python project β€” battle-hardened and bug-free.

Teaches You Python

Studying them reveals Pythonic patterns you'll apply to your own code.

"When you find yourself writing a loop that counts, you're already too late."

πŸ“¦ Collections β€” Specialized Data Structures

Better alternatives to plain dict, list, and tuple for specific tasks.

πŸ“ 1.1 Counter β€” Count Everything

Count occurrences of items in any iterable with a one-liner.

Step-by-step explanation:

  • Step 1: Import Counter from collections.
  • Step 2: Pass an iterable (string, list, etc.).
  • Step 3: Use .most_common(n) for top items.
python
from collections import Counter

# Count letters
text = "mississippi"
c = Counter(text)
print("Counts:", c)
print("Most common 2:", c.most_common(2))

# Count list items
votes = ["red", "blue", "red", "green", "red", "blue"]
vote_counts = Counter(votes)
print("\nVotes:", vote_counts)
print("Winner:", vote_counts.most_common(1))

# Counter arithmetic
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print("\nc1 + c2:", c1 + c2)
print("c1 - c2:", c1 - c2)
print("c1 & c2:", c1 & c2)
πŸ’‘ Counter never raises KeyError β€” missing items return 0, which makes tallying loops trivial.

πŸ“ 1.2 defaultdict β€” Auto-Initializing Dicts

Never again write if key not in d: d[key] = ....

Step-by-step explanation:

  • Step 1: Pass a factory (list, int, set) to the constructor.
  • Step 2: Access missing keys β€” they auto-initialize.
  • Step 3: Useful for grouping (defaultdict(list)) and counting (defaultdict(int)).
python
from collections import defaultdict

# Group words by first letter
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
by_letter = defaultdict(list)

for word in words:
    by_letter[word[0]].append(word)

print("Grouped:", dict(by_letter))

# Count items without initializing
counts = defaultdict(int)
for c in "hello":
    counts[c] += 1
print("\nCounts:", dict(counts))

# Track unique items per category
tags = defaultdict(set)
data = [("python", "lang"), ("java", "lang"), ("linux", "os"), ("macos", "os")]
for name, category in data:
    tags[category].add(name)
print("\nTags:", {k: sorted(v) for k, v in tags.items()})
⚠️ defaultdict creates missing keys on access β€” even reads. Use d.get(key) if you don't want that.

πŸ“ 1.3 deque β€” Fast Queues & Stacks

Double-ended queue with O(1) operations on both ends.

Step-by-step explanation:

  • Step 1: Import deque (pronounced "deck").
  • Step 2: Use append(), appendleft(), pop(), popleft().
  • Step 3: Cap the size with maxlen for rolling buffers.
python
from collections import deque

# Queue (FIFO)
queue = deque(["first", "second"])
queue.append("third")
print("Queue:", list(queue))
print("Popped:", queue.popleft())
print("After:", list(queue))

# Stack (LIFO)
stack = deque([1, 2, 3])
stack.append(4)
print("\nStack:", list(stack))
print("Popped:", stack.pop())
print("After:", list(stack))

# Bounded deque β€” last 3 items only
last3 = deque(maxlen=3)
for i in range(6):
    last3.append(i)
print("\nLast 3:", list(last3))
πŸ’‘ deque(maxlen=n) is perfect for "last N items" logic β€” logs, history, rolling windows.

πŸ“ 1.4 namedtuple β€” Lightweight Records

Tuple-like objects with named fields β€” like a mini class without the boilerplate.

Step-by-step explanation:

  • Step 1: Call namedtuple("Name", ["field1", "field2"]).
  • Step 2: Instantiate like a class.
  • Step 3: Access via .field or index.
python
from collections import namedtuple

# Define a record type
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

print("Point:", p)
print("x:", p.x, "y:", p.y)
print("As tuple:", tuple(p))
print("Index 0:", p[0])

# Named access is more readable than indexes
City = namedtuple("City", ["name", "population", "country"])
cities = [
    City("Tokyo", 37000000, "Japan"),
    City("Paris", 2100000, "France"),
]

for c in cities:
    print(f"{c.name} ({c.country}): {c.population:,}")
✨ Since Python 3.6, typing.NamedTuple and dataclasses offer alternatives with type hints, but collections.namedtuple remains the fastest and most compact.

πŸ“ 1.5 OrderedDict & ChainMap

OrderedDict guarantees insertion order; ChainMap merges multiple dicts into one view.

python
from collections import OrderedDict, ChainMap

# OrderedDict β€” order guaranteed (in 3.7+ dicts are ordered too, but
# OrderedDict has extra features like move_to_end)
od = OrderedDict()
od["first"] = 1
od["second"] = 2
od["third"] = 3
od.move_to_end("first")
print("OrderedDict:", dict(od))

# ChainMap β€” layered lookups
defaults = {"color": "blue", "size": "medium", "debug": False}
user = {"color": "red", "debug": True}

config = ChainMap(user, defaults)
print("\ncolor:", config["color"])
print("size: ", config["size"])
print("debug:", config["debug"])

# Maps exposed
print("\nMaps:", [dict(m) for m in config.maps])
πŸ’‘ ChainMap is perfect for layered configuration: command-line args > user config > defaults.

♾️ Itertools β€” Composable Iterator Tools

Build complex iteration logic from simple, fast building blocks.

πŸ“ 2.1 chain() β€” Concatenate Iterables

Iterate over multiple iterables as if they were one.

Step-by-step explanation:

  • Step 1: Import chain from itertools.
  • Step 2: Pass multiple iterables.
  • Step 3: Wrap in list() to see results.
python
from itertools import chain

# Chain multiple lists
combined = list(chain([1, 2], [3, 4], [5, 6]))
print("Chain:", combined)

# Chain strings
chars = list(chain("abc", "def"))
print("Chars:", chars)

# from_iterable flattens one level
nested = [[1, 2], [3, 4], [5, 6]]
flat = list(chain.from_iterable(nested))
print("Flat:", flat)
πŸ’‘ chain.from_iterable(list_of_lists) is the cleanest way to flatten one level β€” much more efficient than a nested loop.

πŸ“ 2.2 zip_longest() & accumulate()

zip_longest pads with a fill value; accumulate does running totals.

Step-by-step explanation:

  • Step 1: zip_longest() zips uneven iterables.
  • Step 2: accumulate() produces running totals.
  • Step 3: Custom functions work with accumulate(func=...).
python
from itertools import zip_longest, accumulate
import operator

# zip_longest β€” pads shorter iterable
names = ["Alice", "Bob", "Carol"]
ages = [30, 25]
pairs = list(zip_longest(names, ages, fillvalue="?"))
print("Zipped:", pairs)

# accumulate β€” running sum
nums = [1, 2, 3, 4, 5]
print("\nRunning sum:", list(accumulate(nums)))

# accumulate with operator
print("Running product:", list(accumulate(nums, operator.mul)))

# Custom function
print("Running max:", list(accumulate([3, 1, 4, 1, 5, 9], max)))

πŸ“ 2.3 groupby() β€” Group Consecutive Items

Group adjacent items with the same key (sort first if needed).

Step-by-step explanation:

  • Step 1: Sort the data by the grouping key.
  • Step 2: Call groupby(data, key=...).
  • Step 3: Iterate over (key, group) pairs.
python
from itertools import groupby

# Group numbers by parity
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
groups = {k: list(v) for k, v in groupby(numbers, key=lambda x: x % 2)}
print("By parity:", groups)

# Group words by length (sort first!)
words = ["hi", "hello", "hey", "world", "apple"]
sorted_words = sorted(words, key=len)
groups = {k: list(v) for k, v in groupby(sorted_words, key=len)}
print("\nBy length:", groups)

# Group tuples by category
data = [
    ("fruit", "apple"),
    ("fruit", "banana"),
    ("veg", "carrot"),
    ("veg", "lettuce"),
]
data.sort(key=lambda x: x[0])
for category, items in groupby(data, key=lambda x: x[0]):
    print(f"\n{category}:")
    for _, name in items:
        print(" -", name)
⚠️ groupby() only groups consecutive items. Sort by the key first, or you'll get multiple groups for the same value.

πŸ”„ Infinite Iterators β€” count, cycle, repeat

Generators that never stop β€” combine with islice or zip to bound them.

πŸ“ 3.1 count(), cycle(), repeat()

Each produces an infinite iterator with a different pattern.

Step-by-step explanation:

  • Step 1: count() counts up (or down) forever.
  • Step 2: cycle() repeats an iterable forever.
  • Step 3: repeat() repeats one value n times (or forever).
python
from itertools import count, cycle, repeat, islice

# count β€” infinite counter
print("count 10-14:", list(islice(count(10), 5)))
print("count step 2:", list(islice(count(0, 2), 5)))

# cycle β€” repeat a sequence
print("\ncycle:", list(islice(cycle("AB"), 8)))

# repeat β€” repeat one value
print("\nrepeat 3:", list(repeat("hi", 3)))

# Combining with zip to bound infinite iterators
pairs = list(zip(count(1), ["a", "b", "c"]))
print("\nPairs:", pairs)
πŸ’‘ Never convert an infinite iterator to a list directly β€” always bound it with islice(), zip(), or break.

πŸ“ 3.2 islice() β€” Slice Any Iterator

Like list slicing, but for iterators β€” even infinite ones.

Step-by-step explanation:

  • Step 1: islice(iterable, stop) takes the first n items.
  • Step 2: islice(iterable, start, stop) works like a slice.
  • Step 3: Add a step with islice(iterable, start, stop, step).
python
from itertools import islice, count

nums = range(20)

# islice(iterable, stop)
print("First 5:", list(islice(nums, 5)))

# islice(iterable, start, stop)
print("Items 5-9:", list(islice(nums, 5, 10)))

# islice(iterable, start, stop, step)
print("Every other 0-10:", list(islice(nums, 0, 10, 2)))

# Works on infinite iterators
print("\nFirst 8 evens:", list(islice(count(0, 2), 8)))
✨ islice() is your safety net for infinite iterators β€” never forget it.

πŸ“ 3.3 tee() β€” Duplicate Iterators

Split one iterator into multiple independent copies.

Step-by-step explanation:

  • Step 1: Call tee(iterable, n).
  • Step 2: Use each returned iterator independently.
  • Step 3: Buffering is behind the scenes β€” memory grows with offset.
python
from itertools import tee

nums = [1, 2, 3, 4, 5]
a, b, c = tee(nums, 3)

print("a:", list(a))
print("b:", [x * 2 for x in b])
print("c:", [x * 10 for x in c])

🎲 Combinatoric β€” product, combinations, permutations

Enumerate all combinations of items β€” perfect for test cases, puzzles, and brute force.

πŸ“ 4.1 product() β€” Cartesian Product

All pairs (or tuples) from multiple iterables β€” like nested loops but faster.

Step-by-step explanation:

  • Step 1: Pass two or more iterables.
  • Step 2: Use repeat=n for self-product.
  • Step 3: Wrap in list() to see results.
python
from itertools import product

# All suit-rank combinations
suits = ["β™ ", "β™₯", "♦", "♣"]
ranks = ["A", "K", "Q"]
deck = list(product(suits, ranks))
print("First 6 cards:", deck[:6])
print("Total cards:  ", len(deck))

# Cartesian product of two lists
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
variants = list(product(colors, sizes))
print("\nVariants:", variants)

# Self-product (like 2 nested loops)
pairs = list(product("AB", repeat=2))
print("\nABΒ²:", pairs)

πŸ“ 4.2 combinations() & combinations_with_replacement()

All r-length subsets, order doesn't matter, no duplicates (or with duplicates).

Step-by-step explanation:

  • Step 1: Call combinations(iterable, r).
  • Step 2: Results are sorted tuples.
  • Step 3: Use combinations_with_replacement to allow repeats.
python
from itertools import combinations, combinations_with_replacement

# All 2-card hands from 4 cards
cards = ["A", "K", "Q", "J"]
hands = list(combinations(cards, 2))
print("All pairs:", hands)
print("Count:   ", len(hands))  # C(4,2) = 6

# Without repeats (default)
print("\nNo-replace 2 from AB:", list(combinations("AB", 2)))

# With repeats
print("\nWith-replace 2 from AB:", list(combinations_with_replacement("AB", 2)))

πŸ“ 4.3 permutations() β€” All Orderings

Every possible arrangement of r items β€” order matters.

Step-by-step explanation:

  • Step 1: Call permutations(iterable, r).
  • Step 2: Results are all orderings of r items.
  • Step 3: Omit r to use the full length.
python
from itertools import permutations

# All permutations of ABC
print("ABC perms:", list(permutations("ABC")))

# All 2-permutations (ordered pairs)
print("\nAB 2-perms:", list(permutations("AB", 2)))

# Real-world: password brute force
chars = "ab"
for attempt in permutations(chars):
    print("Trying:", "".join(attempt))

🍳 Recipes β€” Combining Collections & Itertools

Real-world patterns that combine both modules into powerful tools.

πŸ“ 5.1 Word Frequency Counter

Count words, top-N most common β€” the classic Counter use case.

Step-by-step explanation:

  • Step 1: Split text into words.
  • Step 2: Pass to Counter.
  • Step 3: Use .most_common(n) for the top items.
python
from collections import Counter

text = """
the quick brown fox jumps over the lazy dog
the dog sleeps and the fox runs
"""
words = text.lower().split()
counts = Counter(words)

print("Top 5 words:")
for word, count in counts.most_common(5):
    print(f"  {word}: {count}")

πŸ“ 5.2 Sliding Window with deque + islice

Compute a rolling average across a stream of numbers.

Step-by-step explanation:

  • Step 1: Use deque(maxlen=window).
  • Step 2: Append each value, keeping the last N.
  • Step 3: Compute the average of the current window.
python
from collections import deque

data = [10, 20, 30, 40, 50, 60, 70]
window = deque(maxlen=3)

print("Rolling average (window=3):")
for x in data:
    window.append(x)
    avg = sum(window) / len(window)
    print(f"  +{x:3d} β†’ window={list(window)} avg={avg:.1f}")

πŸ“ 5.3 Test Case Generator

Generate all combinations of test inputs using product and combinations.

Step-by-step explanation:

  • Step 1: Define test dimensions (browsers, OSes, versions).
  • Step 2: Use product() for exhaustive combinations.
  • Step 3: Use combinations() for pairwise testing.
python
from itertools import product

browsers = ["chrome", "firefox", "safari"]
os_list = ["windows", "macos", "linux"]
versions = ["v1", "v2"]

all_combos = list(product(browsers, os_list, versions))
print(f"Total test cases: {len(all_combos)}")
print("\nFirst 6:")
for combo in all_combos[:6]:
    print("  ", " | ".join(combo))
πŸ’‘ product() replaces nested loops β€” product(a, b) is equivalent to [(x, y) for x in a for y in b] but much faster.

πŸ“ 5.4 Flatten & Group Data

Combine chain.from_iterable, groupby, and Counter for data pipelines.

Step-by-step explanation:

  • Step 1: Flatten nested lists with chain.from_iterable.
  • Step 2: Group with groupby after sorting.
  • Step 3: Count with Counter.
python
from itertools import chain, groupby
from collections import Counter

# Flatten nested lists
orders = [
    ["apple", "banana", "apple"],
    ["banana", "cherry"],
    ["apple", "cherry", "cherry"],
]
all_items = list(chain.from_iterable(orders))
print("All items:", all_items)

# Count items
counts = Counter(all_items)
print("\nItem counts:")
for item, count in counts.most_common():
    print(f"  {item}: {count}")

# Group items by first letter
all_items.sort()
print("\nGrouped by letter:")
for letter, group in groupby(all_items, key=lambda x: x[0]):
    print(f"  {letter}: {list(group)}")

❓ Frequently Asked Questions β€” Collections & Itertools

Common questions about these powerful standard-library modules.

When should I use Counter vs a regular dict?

+

Use Counter whenever you're counting things. It handles missing keys (returns 0), supports arithmetic (add, subtract, intersection), and has most_common(). A plain dict requires if x in d: d[x] += 1 else: d[x] = 1 β€” verbose and error-prone.

What's the difference between deque and a list?

+

List append() and pop() are O(1) at the end but O(n) at the start. deque gives O(1) for both ends. Use deque for queues (FIFO), stacks (LIFO), and rolling buffers. Lists are better for random access and slicing.

Why is namedtuple better than a regular class?

+

namedtuple is a tuple subclass β€” immutable, hashable, memory-efficient, and fast. It's ideal for small records (coordinates, configs, DB rows). For mutable records or methods, use dataclasses or a class.

Why does groupby() give me multiple groups for the same value?

+

groupby() only groups consecutive items. If your data is ['a', 'b', 'a'], you get two separate 'a' groups. Always sorted() or otherwise order your data by the grouping key first.

What's the difference between combinations and permutations?

+

combinations('ABC', 2) β†’ [('A','B'), ('A','C'), ('B','C')] β€” order doesn't matter, no repeats. permutations('ABC', 2) β†’ [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')] β€” order matters, so more results.

How do I bound an infinite iterator?

+

Use islice() β€” islice(count(), 10) takes the first 10. Or combine with zip: zip(infinite, finite) stops when the shorter iterable ends. Never call list() directly on an infinite iterator.

What's the difference between itertools.chain and chain.from_iterable?

+

chain(a, b, c) takes multiple iterables as separate arguments. chain.from_iterable([a, b, c]) takes one iterable of iterables. Use from_iterable when you already have a list of lists to flatten.

Are collections and itertools included in every Python installation?

+

Yes β€” both are part of Python's standard library and available in every installation. No pip install needed. collections has been around since Python 2.4, and itertools since 2.3, with continuous additions.

πŸ’› You've Mastered Collections & Itertools

From Counter for counting and deque for queues, to chain for flattening and product for combinatorics, you now have a full toolkit for writing concise, efficient Python. You can replace dozens of lines of manual loops with single, expressive calls.

This curriculum, crafted by @PoeticGlenn, gives you the foundation to write Python that's both readable and fast. The patterns you've learned β€” counting, grouping, flattening, combining β€” will save you hours in every project you touch.

24 lessons 25+ code examples 1.0k+ learners

"The standard library is Python's gift to you. Collections and itertools are the gift that keeps on giving." β€” Glenn Junsay Pansensoy (@PoeticGlenn)