Data Structures18 min read

Collections Toolkit

Learn collections module structures that feel like “super-powered” lists and dicts: Counter, defaultdict, deque, and namedtuple with real examples.

David Miller
December 21, 2025
0.0k0

Python's `collections` module gives extra data structures. ## 1) Counter (count items easily) ```python from collections import Counter fruits = ["apple", "banana", "apple", "orange", "banana", "apple"] c = Counter(fruits) print(c) print(c.most_common(2)) ``` ## 2) defaultdict (avoid KeyError) ```python from collections import defaultdict scores = defaultdict(int) scores["Tom"] += 10 print(scores) ``` ## 3) deque (fast queue) ```python from collections import deque q = deque(["Tom", "Sarah"]) q.append("Mike") q.appendleft("Ahsan") print(q) left = q.popleft() print(left) ``` ## 4) namedtuple (lightweight objects) ```python from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(10, 20) print(p.x, p.y) ``` ## Graph: deque queue ```mermaid flowchart LR A[Left] --> B[deque] --> C[Right] ``` ## Remember - Counter for counting - defaultdict for grouping and safe defaults - deque for queues and stacks - namedtuple for readable tuple-like objects

#Python#Intermediate#Collections