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
September 28, 2025
6.1k228

Python's collections module gives extra data structures.

1) Counter (count items easily)

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)

from collections import defaultdict

scores = defaultdict(int)
scores["Tom"] += 10
print(scores)

3) deque (fast queue)

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)

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y)

Graph: deque queue

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