[{"data":1,"prerenderedAt":74},["ShallowReactive",2],{"qa-\u002Fpython\u002Fdata-structures\u002Fcollections-module":3},{"page":4,"siblings":57,"blog":48},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":48,"seo":49,"seoDescription":50,"stem":51,"subtopic":52,"topic":53,"topicSlug":54,"updated":55,"__hash__":56},"qa\u002Fpython\u002Fdata-structures\u002Fcollections-module.md","Collections Module",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,5,"\u002Fpython\u002Fdata-structures\u002Fcollections-module",[23,28,32,36,40,44],{"id":24,"difficulty":25,"q":26,"a":27},"counter","easy","What is collections.Counter and what is it good for?","**`Counter`** is a `dict` subclass for **counting hashable items**. You pass it\nany iterable and it tallies occurrences into a `{element: count}` mapping, with\nhandy extras like `most_common()`. Missing keys return **0** instead of raising.\n\n```python\nfrom collections import Counter\nc = Counter(\"mississippi\")\n# Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})\n\nc.most_common(2)     # [('i', 4), ('s', 4)] — top N by count\nc[\"z\"]               # 0 — missing key, no KeyError\nc.update(\"pp\")       # add more counts -> p becomes 4\n\nCounter([1, 1, 2]) + Counter([1, 3])   # Counter({1: 3, 2: 1, 3: 1})\n```\n\nIt replaces the manual `d[x] = d.get(x, 0) + 1` pattern and supports arithmetic\nbetween counters. Reach for `Counter` whenever the task is \"how many of each?\" —\nword frequencies, tallies, or finding the most common elements.\n",{"id":29,"difficulty":25,"q":30,"a":31},"defaultdict","How does collections.defaultdict work, and how is it different from dict.setdefault?","**`defaultdict(factory)`** is a `dict` that **auto-creates a missing key's value**\nby calling the zero-argument `factory` (like `list`, `int`, or `set`) the first\ntime you access it — so you can append or increment without initializing.\n\n```python\nfrom collections import defaultdict\n\ngroups = defaultdict(list)\ngroups[\"fruits\"].append(\"apple\")   # key auto-created as [] then appended\n# {'fruits': ['apple']}\n\ncounts = defaultdict(int)\nfor ch in \"aab\":\n    counts[ch] += 1                # missing keys start at 0\n# {'a': 2, 'b': 1}\n```\n\nThe difference from **`setdefault`**: `setdefault` evaluates its default\n**on every call** even when the key exists (wasteful), whereas `defaultdict`\nonly calls the factory **on a miss**. Use `defaultdict` for grouping and\ncounting loops; use plain `setdefault` for a one-off default insertion.\n",{"id":33,"difficulty":14,"q":34,"a":35},"deque","What is a collections.deque and why use it over a list?","A **`deque`** (\"double-ended queue\") gives **O(1) appends and pops at *both*\nends**, whereas a `list` is O(n) for operations at the front (every element\nshifts). It also supports a **`maxlen`** for a fixed-size sliding window.\n\n```python\nfrom collections import deque\n\nd = deque([1, 2, 3])\nd.appendleft(0)    # O(1) — list.insert(0, x) would be O(n)\nd.append(4)        # O(1)\nd.popleft()        # O(1) — efficient FIFO queue\n\nwindow = deque(maxlen=3)\nfor x in [1, 2, 3, 4]:\n    window.append(x)   # auto-drops from the left\n# deque([2, 3, 4], maxlen=3)\n```\n\nUse a deque for **queues, BFS, and sliding windows**; with `maxlen` it\nauto-discards the oldest item when full (great for \"last N\" buffers). Stick with\na list when you only push\u002Fpop at the end or need fast random indexing.\n",{"id":37,"difficulty":14,"q":38,"a":39},"ordereddict","Is OrderedDict still useful now that regular dicts keep insertion order (3.7+)?","Mostly not for ordering itself — since **Python 3.7** a plain `dict` already\npreserves insertion order, so `OrderedDict` is no longer needed just to remember\norder. But it still has a couple of **distinct features** a regular dict lacks.\n\n```python\nfrom collections import OrderedDict\n\n# 1) order-sensitive equality\nOrderedDict(a=1, b=2) == OrderedDict(b=2, a=1)   # False\ndict(a=1, b=2)        == dict(b=2, a=1)          # True (order ignored)\n\n# 2) move_to_end and a popitem(last=...) toggle\nod = OrderedDict(a=1, b=2, c=3)\nod.move_to_end(\"a\")        # OrderedDict([('b',2),('c',3),('a',1)])\nod.popitem(last=False)     # pop from the FRONT — FIFO\n```\n\nSo use `OrderedDict` when you need **order-sensitive `==`**, **`move_to_end`**,\nor **`popitem(last=False)`** — for example, building an LRU cache. For plain\n\"keep the order I inserted,\" a regular dict is now enough.\n",{"id":41,"difficulty":14,"q":42,"a":43},"chainmap","What is collections.ChainMap?","**`ChainMap`** groups multiple dicts into a **single, layered view** without\ncopying them. Lookups search the underlying mappings **in order** and return the\nfirst match, so earlier maps **shadow** later ones.\n\n```python\nfrom collections import ChainMap\n\ndefaults = {\"color\": \"red\", \"size\": \"M\"}\noverrides = {\"color\": \"blue\"}\nsettings = ChainMap(overrides, defaults)\n\nsettings[\"color\"]    # 'blue' — first map wins\nsettings[\"size\"]     # 'M'    — falls through to defaults\n\nsettings[\"size\"] = \"L\"   # writes go to the FIRST map (overrides) only\n```\n\nIt's perfect for **layered configuration** (CLI args over env vars over\ndefaults) and scope-like lookups, because it stays live — changing a source dict\nshows up immediately. Note that **writes and deletes only affect the first\nmapping**. Use it to merge config layers without flattening them into one dict.\n",{"id":45,"difficulty":25,"q":46,"a":47},"namedtuple-crossref","How does namedtuple fit into the collections module?","**`collections.namedtuple`** is a factory that creates an **immutable tuple\nsubclass with named fields** — lightweight, hashable records that read like\nobjects but behave like tuples (indexing, unpacking, comparison).\n\n```python\nfrom collections import namedtuple\n\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\np = Point(3, 4)\np.x, p[0]        # 3, 3  — named and positional access\np._asdict()      # {'x': 3, 'y': 4}\np._replace(x=9)  # Point(x=9, y=4) — returns a NEW tuple (immutable)\n```\n\nIt rounds out the module's record-like tools alongside `Counter`,\n`defaultdict`, and `deque`. For richer needs — type hints, defaults, methods —\n`typing.NamedTuple` or a `@dataclass` is the modern choice. Use `namedtuple` for\nsimple, immutable, self-documenting records.\n",null,{"description":11},"Python interview questions on the collections module — Counter, defaultdict, deque, OrderedDict, ChainMap, and how they relate to namedtuple.","python\u002Fdata-structures\u002Fcollections-module","The collections Module","Data Structures","data-structures","2026-06-18","LZW7rGcpTd9BsXIZIOFd-X_5qK8sKAY3AZmE-BjNbyY",[58,62,65,69,73],{"subtopic":59,"path":60,"order":61},"Lists & Slicing","\u002Fpython\u002Fdata-structures\u002Flists",1,{"subtopic":63,"path":64,"order":12},"Tuples & Named Tuples","\u002Fpython\u002Fdata-structures\u002Ftuples",{"subtopic":66,"path":67,"order":68},"Dictionaries","\u002Fpython\u002Fdata-structures\u002Fdictionaries",3,{"subtopic":70,"path":71,"order":72},"Sets & Frozensets","\u002Fpython\u002Fdata-structures\u002Fsets",4,{"subtopic":52,"path":21,"order":20},1781808679494]