🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Data Structures: Trees, Heaps, Tries, and Hash Maps

Python Data StructuresđŸŸĸ Free Lesson

Prerequisites

  • !Lists, dictionaries, and their complexity characteristics
  • !Recursion and tree traversals

What You'll Learn

  • 1Match a data structure to the access pattern instead of habit
  • 2Implement insert, search, and traversal on a binary search tree
  • 3Use heaps for top-k selection and priority scheduling
  • 4Build a trie and explain its memory versus speed trade-off
  • 5Write a chaining hash map and reason about its worst case

Python gives you lists, dicts, and sets that cover the majority of needs, and reaching for anything else should be a deliberate act. The structures below earn their place only when their access pattern is the bottleneck: ordered navigation, repeated minimum extraction, prefix lookup, or custom eviction rules. Each section pairs an implementation with the reason you would choose it, and the closing table ties operation cost to the shape of your data.

Match the structure to the question you ask

Before writing nodes, name the question your code asks thousands of times per second.

StructureFastest operationTypical costWeak spot
Hash map (dict)Exact lookup by keyAmortised constantNo ordering, no range queries
Balanced BSTOrdered navigation, range scanLogarithmicMore code, pointer chasing
HeapInsert and extract extremeLogarithmicNo lookup, only the extreme
TriePrefix searchProportional to key lengthMemory hungry for wide alphabets
Sorted list + bisectOrdered insert and searchLinear insert, log searchInsert shifts elements
ArrayIndexed accessConstantInsert and delete are expensive

The dictionary already wins for exact keys, which is why a hand-rolled hash map is a learning exercise rather than a production decision. Trees appear when you need the keys in order or need to ask "what is within this range". Heaps appear when you only ever care about the smallest or largest item. Tries appear when the keys share long prefixes and you must match on those prefixes.

Binary search trees: correct first, balanced second

A search tree keeps smaller values left and larger values right, so navigation costs one comparison per level. Insertion and search are the same walk, and an in-order traversal yields the values sorted, which makes the structure easy to verify.

python
class Node:
    __slots__ = ("value", "left", "right")

    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None


class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, value):
        self.root = self._insert(self.root, value)

    def _insert(self, node, value):
        if node is None:
            return Node(value)
        if value < node.value:
            node.left = self._insert(node.left, value)
        elif value > node.value:
            node.right = self._insert(node.right, value)
        return node

    def contains(self, value):
        node = self.root
        while node is not None:
            if value == node.value:
                return True
            node = node.left if value < node.value else node.right
        return False

    def inorder(self):
        seen, stack, node = [], [], self.root
        while stack or node:
            while node is not None:
                stack.append(node)
                node = node.left
            node = stack.pop()
            seen.append(node.value)
            node = node.right
        return seen


tree = BinarySearchTree()
for value in [5, 3, 7, 1, 4, 6, 8]:
    tree.insert(value)
print(tree.inorder())        # [1, 3, 4, 5, 6, 7, 8]
print(tree.contains(4), tree.contains(9))   # True False

The honest caveat is balance. Inserting sorted input into this tree degenerates it into a linked list, and every operation becomes linear. Production systems fix that with rotations, as in AVL or red-black trees, or with B-trees for disk-backed storage. The iterative in-order traversal above is deliberate: the recursive version is shorter but adds a stack frame per level, which is the same depth problem you meet in deep recursion.

Heaps: one structure, one guarantee

A heap is an array that satisfies a single property: every parent is no worse than its children. That is enough to make the extreme item trivially available, and it is why priority queues, scheduling, and top-k selection are built on it. Python's heapq module operates directly on ordinary lists.

python
import heapq

tasks = []
heapq.heappush(tasks, (2, "parse input"))
heapq.heappush(tasks, (1, "fetch config"))
heapq.heappush(tasks, (1, "warm cache"))

while tasks:
    priority, name = heapq.heappop(tasks)
    print(priority, name)

scores = [55, 72, 91, 68, 99, 84]
print(heapq.nlargest(3, scores))          # [99, 91, 84]
print(heapq.nsmallest(2, scores))         # [55, 68]

top3 = []
for score in scores:
    if len(top3) < 3:
        heapq.heappush(top3, score)
    else:
        heapq.heappushpop(top3, score)
print(sorted(top3, reverse=True))         # [99, 91, 84]

Note the tie-breaking: tuples compare element by element, so a priority of 1 with a name is ordered by the name when priorities match, which is exactly what you want for deterministic scheduling. For a max-heap in a min-heap library, negate the value or store a sort key that inverts the order.

Tries: prefix speed at a memory cost

A trie stores each character of a key as a node, so shared prefixes collapse into shared structure. Lookup cost depends on the length of the query rather than the size of the dictionary, which matters for autocomplete, IP routing tables, and word games.

python
class TrieNode:
    __slots__ = ("children", "is_end")

    def __init__(self):
        self.children = {}
        self.is_end = False


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            node = node.children.setdefault(char, TrieNode())
        node.is_end = True

    def starts_with(self, prefix):
        node = self.root
        for char in prefix:
            node = node.children.get(char)
            if node is None:
                return False
        return True

    def count_with_prefix(self, prefix):
        node = self.root
        for char in prefix:
            node = node.children.get(char)
            if node is None:
                return 0
        return self._count(node)

    def _count(self, node):
        total = 1 if node.is_end else 0
        for child in node.children.values():
            total += self._count(child)
        return total


trie = Trie()
for word in ["app", "apple", "apply", "banana"]:
    trie.insert(word)
print(trie.starts_with("app"), trie.starts_with("apz"))   # True False
print(trie.count_with_prefix("app"))                      # 3

The cost shows up in memory: a dictionary per node is far heavier than a character in a flat array. For a fixed alphabet you can compress children into a single string lookup or an array indexed by character, and for large English dictionaries a compressed variant such as a radix tree removes most of the intermediate nodes.

Hash maps, built once, to understand dict

Writing a chaining hash map clarifies what your dictionary is doing behind the scenes and why collision handling matters.

python
class HashMap:
    def __init__(self, capacity=8, load_factor=0.75):
        self._buckets = [[] for _ in range(capacity)]
        self._size = 0
        self._load_factor = load_factor

    def _index(self, key):
        return hash(key) % len(self._buckets)

    def __setitem__(self, key, value):
        bucket = self._buckets[self._index(key)]
        for i, (k, _) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))
        self._size += 1
        if self._size / len(self._buckets) > self._load_factor:
            self._resize()

    def __getitem__(self, key):
        for k, v in self._buckets[self._index(key)]:
            if k == key:
                return v
        raise KeyError(key)

    def _resize(self):
        old = self._buckets
        self._buckets = [[] for _ in range(len(old) * 2)]
        self._size = 0
        for bucket in old:
            for k, v in bucket:
                self[k] = v


m = HashMap()
m["host"] = "example.com"
m["port"] = 5432
print(m["host"], m["port"])   # example.com 5432

Resizing is the reason dict growth is amortised rather than constant: individual inserts occasionally pay for rehashing everything. If your keys are badly distributed, every operation degrades to a scan of one bucket, which is the worst case a plain dict can also hit.

Choosing under real constraints

The right structure depends on the ratio between reads and writes, whether order matters, how much memory you can spend, and how the data is distributed. Profile with realistic volumes: a trie that shines on ten thousand words may lose to a sorted list with binary search on a million, and a heap-based top-k beats a full sort only while k stays small relative to n. Write down the decision when you make it, because the reason a structure was chosen is exactly what the next engineer will need when the data doubles again.

Measuring before you commit to a structure

Micro-benchmarks in Python are easy to get wrong, so treat them as directional evidence rather than proof. Time a loop that performs many operations rather than a single call, because per-call overhead and interpreter noise will dominate otherwise. Warm up first if any just-in-time behaviour or cache fill matters, and compare against a baseline built from the standard library rather than against nothing. Use timeit with a fixed number of repetitions so runs are comparable, and report the distribution rather than a single number when the variance looks suspicious.

The second half of measurement is representing your real data. A trie benchmarked on short English words says nothing about URL matching with long shared prefixes, and a tree benchmarked on randomly shuffled keys hides the degenerate case that sorted input produces. Generate inputs that mirror production: the same key lengths, the same skew, the same ratio of updates to reads. If the workload is read heavy, measure the read path in isolation; if writes dominate, measure growth across several resizes, since that is where amortised cost hides its spikes.

Finally, remember that structure choice interacts with everything around it. A custom node class costs allocation time that a flat array avoids, pointer chasing defeats cache locality, and objects with attributes cost more memory than the packed alternatives. A structure that wins on operation count can still lose on wall-clock time in Python because the constant factors are large. Measure end to end, keep the standard library version until the numbers force a change, and document the benchmark alongside the code so the next reader knows what the decision was based on.

Common Mistakes

Reaching for a custom tree when a dict and a sorted list would answer the query

Fix: Measure first; only move to a tree when ordered range queries show up in the profile.

Assuming a heap can search for or remove an arbitrary element

Fix: Keep a side index from key to position, or use a balanced structure if random removal is required.

Building a trie whose node objects dominate your memory budget

Fix: Compress children into arrays or strings for a fixed alphabet, or use a radix tree for shared suffixes.

Hashing mutable keys or keys with unstable hash values across runs

Fix: Use immutable canonical keys such as tuples of strings, and keep PYTHONHASHSEED out of logic that depends on ordering.

Best Practices

  • Name the access pattern out loud before selecting a structure
  • Keep the iterative traversal variants handy for deep or untrusted input
  • Prefer heapq over a hand-written heap, but learn the tie-breaking rules it implies
  • Add __slots__ to node classes when the structure holds millions of them
  • Unit test invariants: sorted in-order output, heap ordering, and trie prefix counts

Key Takeaways

  • Dicts win for exact keys; trees for order, heaps for extremes, tries for prefixes
  • An unbalanced binary search tree degrades to linear time on sorted input
  • Heaps guarantee only the extreme item, which is enough for scheduling and top-k
  • Tries trade memory for prefix speed and compress naturally when keys overlap
  • Every structure has a worst case; know it before the data arrives
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement