Advanced Python Data Structures for Interviews & Code

Level up your Python with the structures interviewers love — and that clean code relies on.

Python's built-ins cover 90% of cases, but the collections and heapq modules hold the structures that make hard problems easy — and make your code read like you've been doing this a while.

defaultdict — no more key checks

python
from collections import defaultdict

# count words without checking for missing keys
counts = defaultdict(int)
for word in "the quick brown fox the fox".split():
    counts[word] += 1

# group items by key
groups = defaultdict(list)
for name in ["ann", "bob", "amy", "ben"]:
    groups[name[0]].append(name)

print(counts["the"])   # 2  (no KeyError)
print(dict(groups))    # {'a': ['ann','amy'], 'b': ['bob','ben']}

Counter — counts and top-N

python
from collections import Counter

c = Counter("abracadabra")
print(c.most_common(3))     # [('a', 5), ('b', 2), ('r', 2)]
print(c["z"])               # 0, not KeyError

deque — fast both ends

python
from collections import deque

d = deque(["a", "b", "c"])
d.appendleft("z")           # O(1)
d.pop()                     # O(1) from the right
d.append("y")
print(list(d))              # ['z', 'a', 'b', 'y']

# a fixed-size sliding buffer
buf = deque(maxlen=3)
for x in range(5):
    buf.append(x)
print(list(buf))            # [2, 3, 4]

heapq — always the smallest

python
import heapq

h = []
for x in [5, 2, 9, 1]:
    heapq.heappush(h, x)
print(heapq.heappop(h))   # 1 (always the minimum)

# top-3 largest without sorting everything
nums = [5, 2, 9, 1, 7, 3]
print(heapq.nlargest(3, nums))   # [9, 7, 5]

namedtuple — self-documenting tuples

python
from collections import namedtuple

Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p.y)          # readable, and still hashable/immutable
Heaps are the answer to any "k largest / k closest / merge k streams" problem — heapq keeps them a one-liner instead of a page of code.

These aren't exotic — they're the difference between a loop full of bookkeeping and a clean two-line solution.

Your move

Want us to build this for you?

We turn tutorials like these into production systems every day. Tell us what you need.

Start a project →