Skip to main content

Standard Library

collections Module

Complete lesson for collections Module using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — collections Module

Section: Standard Library. Master Python collections: Counter, defaultdict, deque, namedtuple, OrderedDict, and ChainMap for interview-ready data structures.

What is the collections module?

  • collections is a standard-library module of specialized container types that extend list, dict, and tuple for common patterns.
  • You import what you need: from collections import Counter, defaultdict, deque, namedtuple, OrderedDict, ChainMap.
  • These types show up constantly in coding interviews and production Python (frequency maps, BFS queues, lightweight records).
  • Prefer them over hand-rolled helpers when the API already matches your problem.
from collections import Counter, defaultdict, deque, namedtuple

print(Counter("banana"))
print(defaultdict(int))
print(deque([1, 2, 3]))
Point = namedtuple("Point", "x y")
print(Point(1, 2))

Counter — count hashable items

  • Counter is a dict subclass that maps elements to integer counts.
  • Construct from an iterable (Counter('abracadabra')) or from a mapping of counts.
  • most_common(n) returns the n highest-count pairs; omit n for all, sorted by count.
  • Arithmetic: c1 + c2 adds counts; c1 - c2 subtracts (keeps only positive); & takes min, | takes max per key.
from collections import Counter

votes = ["yes", "no", "yes", "yes", "no", "maybe"]
c = Counter(votes)
print(c)
print(c["yes"], c["absent"])  # missing key -> 0
print(c.most_common(2))
print(list(c.elements()))

defaultdict — dict with a default factory

  • defaultdict(factory) calls factory() when you read a missing key, then stores and returns that value.
  • Common factories: int (0), list ([]), set (set()), or a lambda / custom callable.
  • Ideal for grouping: groups[key].append(item) without setdefault.
  • Still a real dict: .keys(), .items(), JSON-unfriendly until you convert with dict(dd).
from collections import defaultdict

groups = defaultdict(list)
for name, dept in [("Ada", "ML"), ("Bob", "Web"), ("Cara", "ML")]:
    groups[dept].append(name)
print(dict(groups))

counts = defaultdict(int)
for ch in "mississippi":
    counts[ch] += 1
print(dict(counts))

deque — double-ended queue

  • deque (pronounced “deck”) supports O(1) append/pop from both ends.
  • append / pop work on the right; appendleft / popleft on the left.
  • maxlen makes a bounded deque that discards from the opposite end when full.
  • Use as a queue (FIFO: append + popleft) or stack (LIFO: append + pop).
from collections import deque

q = deque(["a", "b"])
q.append("c")
q.appendleft("z")
print(q)
print(q.popleft(), q.pop())
ring = deque(maxlen=3)
for n in range(5):
    ring.append(n)
print(ring)

namedtuple — immutable record tuples

  • namedtuple(typename, field_names) builds a tuple subclass with named fields and a helpful repr.
  • Access by index or attribute: p[0] and p.x are the same for Point(x, y).
  • Instances are immutable like normal tuples — good for dictionary keys if all fields are hashable.
  • _asdict(), _replace(**kwargs), and _fields are the usual helpers.
from collections import namedtuple

Student = namedtuple("Student", ["name", "marks"])
s = Student("Neha", 92)
print(s.name, s.marks, s[0])
print(s._asdict())
print(s._replace(marks=95))

OrderedDict — insertion-ordered mapping

  • Since Python 3.7, regular dict also keeps insertion order. Prefer plain dict for new code unless you need OrderedDict-only APIs.
  • OrderedDict still offers move_to_end(key, last=True) and equality that can care about order (historically).
  • Useful when teaching LRU-style patterns or when an API explicitly returns OrderedDict (e.g. some CSV / config tools).
  • For LRU caches in real code, prefer functools.lru_cache or a dedicated cache library.
from collections import OrderedDict

od = OrderedDict()
od["first"] = 1
od["second"] = 2
od["third"] = 3
od.move_to_end("first")
print(list(od.keys()))
od.move_to_end("third", last=False)
print(list(od.keys()))

ChainMap — search multiple mappings

  • ChainMap(m1, m2, ...) looks up keys in order across underlying maps without merging copies.
  • Writes (cm[k] = v) always go to the first map — useful for layered defaults + overrides.
  • Typical uses: CLI flags over env over config file; nested scopes in interpreters.
  • new_child() pushes a fresh map in front for a nested scope.
from collections import ChainMap

defaults = {"theme": "light", "lang": "en"}
user = {"theme": "dark"}
cfg = ChainMap(user, defaults)
print(cfg["theme"], cfg["lang"])
cfg["lang"] = "hi"
print(user, defaults)

When to pick which type

  • Frequency / majority / top-k → Counter.
  • Group lists or accumulate ints without boilerplate → defaultdict.
  • BFS / sliding window / both-end edits → deque.
  • Lightweight immutable rows → namedtuple (or @dataclass(frozen=True) for richer records).
TypeBest forMutable?
CounterTallies and top-kYes
defaultdictGrouping / accumulatorsYes
dequeQueue, stack, maxlen bufferYes
namedtupleFixed fields, readable tuplesNo (fields)
OrderedDictExplicit reordering APIsYes
ChainMapLayered lookupsYes (first map)

Counter patterns interviewers love

  • Counter(s1) == Counter(s2) tests anagrams in one line.
  • c.most_common(1)[0] is the mode (check empty first).
  • sum(c.values()) is the total number of counted elements.
  • c.update(iterable) adds more observations in place.
from collections import Counter

def is_anagram(a, b):
    return Counter(a) == Counter(b)

print(is_anagram("listen", "silent"))
print(is_anagram("hello", "world"))
c = Counter("aab")
c.update("abb")
print(c)

defaultdict vs setdefault vs Counter

  • d.setdefault(k, []).append(x) works on plain dicts but repeats the default expression style awkwardly for counters.
  • defaultdict(list) is cleaner for grouping; Counter / defaultdict(int) are cleaner for counts.
  • Do not use defaultdict if missing keys should raise — silent inserts can hide bugs.
  • Convert with dict(dd) when an API requires a plain dict.
NeedPreferWhy
Count itemsCountermost_common, arithmetic
Group by keydefaultdict(list)append without checks
Strict missing keysplain dictKeyError is a feature
JSON dumpdict(...)stdlib json wants plain dict
L2

Advanced — collections Module

Counter internals and gotchas

  • Counter missing keys return 0, they are not inserted until you assign or update.
  • Counts can go negative if you assign negatives; elements() skips non-positive counts.
  • subtract can leave zeros and negatives; + between counters drops non-positive results.
  • Counter is unordered in the sense of “priority by count”, but iteration follows dict insertion order of keys.
from collections import Counter

c = Counter(a=3, b=1)
c.subtract(a=5, b=1)
print(c)
print(list(c.elements()))
print(+c)  # drops non-positive

defaultdict factory pitfalls

  • The factory is called with zero arguments — defaultdict(list) not defaultdict(list()).
  • Passing list() would insert one shared list incorrectly; passing list creates a fresh list per missing key.
  • Nested defaults: defaultdict(lambda: defaultdict(int)) for 2D sparse matrices.
  • dd[k] on read inserts — use k in dd or dd.get(k) when probing without insert.
from collections import defaultdict

# WRONG pattern would be defaultdict(list()) — shared default object
grid = defaultdict(lambda: defaultdict(int))
grid["r1"]["c2"] += 5
print(grid["r1"]["c2"], grid["r1"]["missing"])
print("r2" in grid)  # False — not inserted by 'in'
_ = grid["r2"]
print("r2" in grid)  # True — read inserted empty defaultdict

deque performance and rotation

  • Indexed access in the middle of a deque is O(n); prefer list if you need random access.
  • rotate(n) shifts right for positive n, left for negative — handy for Josephus / circular buffers.
  • extend / extendleft — note extendleft reverses the order of the iterable as it prepends one-by-one.
  • Thread safety: deque operations are documented as atomic for append/pop ends, but compound sequences still need locks.
from collections import deque

d = deque(range(5))
d.rotate(2)
print(d)
d.rotate(-1)
print(d)
d.extendleft([9, 8])
print(d)

namedtuple typing and alternatives

  • Field names must be valid identifiers and not start with underscore (reserved for helpers).
  • Rename invalid names with rename=True, or prefer dataclasses for validation and defaults.
  • typing.NamedTuple adds annotations: class Pt(NamedTuple): x: int; y: int.
  • For mutable records with defaults, use @dataclass instead of namedtuple.
from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

    def manhattan(self):
        return abs(self.x) + abs(self.y)

p = Point(3, -4)
print(p, p.manhattan())

OrderedDict equality and move_to_end

  • Regular dict equality ignores order; OrderedDict equality historically considered order (know your Python version).
  • popitem(last=True) pops from the end; last=False pops from the start — classic LRU building block.
  • A tiny LRU: on hit move_to_end; on miss insert and if over capacity popitem(last=False).
  • Prefer functools.lru_cache for function memoization rather than hand-rolled OrderedDict caches.
from collections import OrderedDict

class LRU:
    def __init__(self, capacity):
        self.capacity = capacity
        self.data = OrderedDict()

    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, value):
        if key in self.data:
            self.data.move_to_end(key)
        self.data[key] = value
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

cache = LRU(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")
cache.put("c", 3)
print(list(cache.data.items()))

ChainMap write rules and new_child

  • Lookup walks maps left to right; assignment always mutates maps[0].
  • new_child(m=None) returns a ChainMap with a new empty (or given) map in front — nested scopes.
  • parents is the ChainMap without the first map.
  • Deleting a key only removes it from the first map that contains it if you use careful APIs — prefer explicit map edits.
from collections import ChainMap

root = {"x": 1}
scope = ChainMap({"y": 2}, root).new_child()
scope["z"] = 3
print(scope.maps)
print(scope["x"], scope["y"], scope["z"])
print(scope.parents["x"])

collections.abc and isinstance checks

  • collections.abc defines abstract interfaces: Mapping, Sequence, Iterable, Hashable, etc.
  • Use isinstance(obj, Mapping) rather than isinstance(obj, dict) when you accept any mapping.
  • Counter, defaultdict, and OrderedDict are MutableMapping instances.
  • deque is not a Sequence in older typing sense for some checkers — treat it as a mutable sequence-like container.
from collections import Counter, deque
from collections.abc import Mapping, MutableMapping

c = Counter(a=1)
print(isinstance(c, Mapping), isinstance(c, MutableMapping))
print(isinstance(deque([1]), list))  # False

Memory and copy notes

  • deque uses a linked block structure — better for ends, worse for middle inserts than list.
  • copy.copy(dd) is shallow; nested lists inside defaultdict are shared.
  • namedtuple instances are compact like tuples — cheaper than equivalent dicts for many rows.
  • Convert large Counters to plain dict only when needed; Counter methods are convenient for analytics.
L3

Tricky Interview Points

Q1) What is the collections module?

Answer A standard-library module providing specialized containers: Counter, defaultdict, deque, namedtuple, OrderedDict, ChainMap, and related helpers.

Q2) How does Counter differ from a normal dict?

Answer Counter is a dict subclass for counts. Missing keys return 0 instead of KeyError, and it adds most_common, elements, and multiset arithmetic.

Q3) What does defaultdict(int) do?

Answer When you access a missing key, it inserts and returns 0 (by calling int()). Ideal for frequency tallies without setdefault.

Q4) Why is deque better than list as a queue?

Answer list.pop(0) is O(n) because elements shift. deque.popleft() is O(1).

Q5) Is namedtuple mutable?

Answer No. Like tuple, fields cannot be assigned. Use _replace to build a modified copy.

Q6) Do you still need OrderedDict in Python 3.10+?

Answer Rarely. Plain dict keeps insertion order since 3.7. Use OrderedDict when you need move_to_end / popitem(last=False) semantics explicitly.

Q7) How does ChainMap lookup work?

Answer It searches underlying mappings from first to last and returns the first hit. Writes go to the first mapping.

Q8) How do you find anagrams with Counter?

Answer Counter(s1) == Counter(s2) compares character frequencies.

Q9) What is wrong with defaultdict(list())?

Answer list() is called once at construction, so every missing key could share one list object if used incorrectly. Pass the factory list, not list().

Q10) How do you get the top 3 frequent words?

Answer Counter(words).most_common(3).

Q11) Can namedtuple be used as a dict key?

Answer Yes, if all field values are hashable, because the namedtuple itself is hashable like a tuple.

Q12) What does deque(maxlen=5) do?

Answer It keeps at most 5 items. Appending when full discards from the opposite end.

Q13) Counter.most_common() order?

Answer Sorted by count descending; ties keep first-encounter order among equal counts in CPython.

Q14) How to convert defaultdict to JSON-safe dict?

Answer Use dict(dd) or {k: dict(v) ...} for nested defaultdicts before json.dump.

Q15) deque vs queue.Queue?

Answer deque is for single-threaded algorithms (BFS). queue.Queue is synchronized for threads and has different APIs (put/get).

L4

Simple Programs

Word frequency with Counter

from collections import Counter

text = "to be or not to be that is the question"
words = text.lower().split()
freq = Counter(words)
print("Total unique:", len(freq))
for word, n in freq.most_common():
    print(f"{word}: {n}")

Group students by grade band

from collections import defaultdict

scores = [("Asha", 91), ("Bala", 76), ("Chitra", 88), ("Dev", 64), ("Esha", 95)]
bands = defaultdict(list)
for name, score in scores:
    if score >= 90:
        band = "A"
    elif score >= 75:
        band = "B"
    else:
        band = "C"
    bands[band].append(name)
for band in sorted(bands):
    print(band, "->", bands[band])

BFS shortest path with deque

from collections import deque

graph = {
    "A": ["B", "C"],
    "B": ["D"],
    "C": ["D", "E"],
    "D": ["F"],
    "E": ["F"],
    "F": [],
}

def bfs(start, goal):
    q = deque([(start, [start])])
    seen = {start}
    while q:
        node, path = q.popleft()
        if node == goal:
            return path
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)
                q.append((nxt, path + [nxt]))
    return None

print(bfs("A", "F"))

namedtuple inventory rows

from collections import namedtuple

Item = namedtuple("Item", "sku name qty price")
stock = [
    Item("A1", "Pen", 10, 5.0),
    Item("A2", "Notebook", 4, 40.0),
    Item("A3", "Eraser", 20, 3.0),
]
total = 0.0
for it in stock:
    line = it.qty * it.price
    total += line
    print(f"{it.sku} {it.name}: {line:.2f}")
print("Grand total:", round(total, 2))

Anagram groups with defaultdict

from collections import defaultdict

words = ["eat", "tea", "tan", "ate", "nat", "bat"]
groups = defaultdict(list)
for w in words:
    key = "".join(sorted(w))
    groups[key].append(w)
for g in groups.values():
    print(g)

Sliding window max with deque

from collections import deque

def max_sliding_window(nums, k):
    out = []
    dq = deque()  # indices, values decreasing
    for i, x in enumerate(nums):
        while dq and dq[0] <= i - k:
            dq.popleft()
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

print(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))

ChainMap config layers

from collections import ChainMap

defaults = {"host": "localhost", "port": 8080, "debug": False}
env = {"port": 9000}
cli = {"debug": True}
cfg = ChainMap(cli, env, defaults)
print("host", cfg["host"])
print("port", cfg["port"])
print("debug", cfg["debug"])
print("maps", cfg.maps)
L5

Problem Solving Tricks

  • Import only what you use: from collections import Counter, deque.
  • Counter(s) on a string counts characters; on a list counts elements.
  • Missing Counter keys return 0 — great for tallies, surprising if you expected KeyError.
  • Always pass the factory class to defaultdict: defaultdict(list), never defaultdict(list()).
  • Queue with deque: append + popleft. Stack with deque: append + pop.
  • deque(maxlen=n) is a one-liner ring buffer.
  • Anagram check: Counter(a) == Counter(b).
  • Convert namedtuple to dict with _asdict() before JSON serialization.
  • Prefer plain dict over OrderedDict unless you need move_to_end.
  • Use ChainMap for layered config instead of merging dicts manually.
L6

Practice Programs List

  1. Count word frequencies in a paragraph with Counter and print the top 5.
  2. Group a list of (city, name) pairs with defaultdict(list).
  3. Implement BFS on a small graph using deque.
  4. Define a namedtuple Employee and print a payroll total.
  5. Write is_anagram(a, b) using Counter.
  6. Build a maxlen=10 deque that records the last 10 log lines.
  7. Implement a tiny LRU cache with OrderedDict.
  8. Merge CLI, env, and default settings with ChainMap.
  9. Use Counter arithmetic to compare two shopping baskets.
  10. Rewrite a setdefault-based grouper as defaultdict.
  11. Solve sliding-window maximum with a monotonic deque.
  12. Convert nested defaultdict to a plain dict for json.dumps.