๐Ÿ—„๏ธCounter, defaultdict, deque, namedtuple, OrderedDictLESSON

Python Collections Module

The collections module provides specialized container datatypes that solve common programming problems more elegantly than plain dict, list, or tuple. Each type is designed for a specific use case.

collections.Counter

Counter counts hashable objects. It's a dict subclass where elements are keys and counts are values:

Counter Arithmetic

Counters support set-like operations:

collections.defaultdict

defaultdict extends dict with a factory function for missing keys, eliminating the need for setdefault() or if key not in d checks:

The factory function can be any callable:

collections.deque

deque (double-ended queue) supports efficient O(1) append and pop from both ends. Regular lists have O(n) cost for insert(0, x) and pop(0):

maxlen: Bounded Deque

The maxlen parameter creates a fixed-size deque โ€” old items are automatically discarded when new ones are added:

This is perfect for sliding windows, recent-items caches, and undo history.

collections.namedtuple

namedtuple creates a tuple subclass with named fields โ€” lightweight, immutable records without the weight of a full class:

Use namedtuple when you need immutable records that should be memory-efficient and tuple-compatible. For mutable records or validation, prefer @dataclass.

collections.OrderedDict

Before Python 3.7, regular dict did not guarantee insertion order. OrderedDict was the solution. Since Python 3.7+, regular dicts maintain insertion order, but OrderedDict still has one advantage: move_to_end():

OrderedDict is useful for LRU cache implementations and when you specifically need move_to_end semantics.

collections.ChainMap

ChainMap groups multiple dictionaries into a single view. Lookups search through the maps in order:

ChainMap is ideal for layered configuration (env > config file > defaults) without copying data.

Quick Reference

TypeUse CaseKey Feature
CounterCount occurrencesmost_common(), arithmetic
defaultdictGroup/accumulateAuto-initializes missing keys
dequeQueue/stackO(1) both-end ops, maxlen
namedtupleLightweight recordsNamed fields, still a tuple
OrderedDictOrdered mappingmove_to_end()
ChainMapLayered configMulti-dict view

Knowledge Check

What does `Counter('aabbc')['z']` return?

A `deque` with `maxlen=3` currently holds `[1, 2, 3]`. What happens when you call `d.append(4)`?

Why use `defaultdict(list)` instead of a regular `dict` when grouping items?