Trie Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie runs in O(m) time and O(n*m) space, in Python as in every other language.
- ✓The standard library ships no trie. You build one from dict: either a node class with __slots__ = ('children', 'is_word') holding dict[str, TrieNode], or the classic nested plain dict with a sentinel key such as a module-level _END = object().
- ✓Reviewers want __slots__ on the node so a million nodes do not each carry a __dict__, and they want the descent loop written with children.get(ch) rather than try/except KeyError in the hot path.
- ✓The Python trap: The defaultdict trie is a read-mutating trie. Because defaultdict.__getitem__ inserts the default on a miss, calling search('cats') on a trie that only has 'cat' silently creates the 's' node and every node under the miss path, so a read-only query grows the structure and later prefix enumeration reports phantom branches.
- ✓The big-O hides an interpreter constant: each edge step is a bytecode-level dict lookup plus an attribute load, roughly 40-80 ns on a current CPython (measured 43 ns for children.get(ch) plus the attribute load on 3.14), so a 20-char word costs about a microsecond, not nanoseconds.
What Trie actually is
Trie in Python: what you actually reach for
Python implementation
from collections import deque
class TrieNode:
__slots__ = ("children", "is_word")
def __init__(self) -> None:
self.children: dict[str, "TrieNode"] = {}
self.is_word = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
nxt = node.children.get(ch)
if nxt is None:
nxt = TrieNode()
node.children[ch] = nxt
node = nxt
node.is_word = True
def _walk(self, prefix: str) -> "TrieNode | None":
node = self.root
for ch in prefix:
node = node.children.get(ch) # .get, never [], or you mutate on read
if node is None:
return None
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.is_word
def with_prefix(self, prefix: str):
start = self._walk(prefix)
if start is None:
return
stack = deque([(start, prefix)]) # explicit stack: no recursion limit
while stack:
node, acc = stack.pop()
if node.is_word:
yield acc
for ch, child in node.children.items():
stack.append((child, acc + ch))Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Trie?
The standard library ships no trie. You build one from dict: either a node class with __slots__ = ('children', 'is_word') holding dict[str, TrieNode], or the classic nested plain dict with a sentinel key such as a module-level _END = object(). collections.defaultdict supports the one-liner Trie = lambda: defaultdict(Trie). For production, the ecosystem answers are pygtrie (pure Python, CharTrie/StringTrie/PrefixSet, dict-like API) and marisa-trie (a C++ MARISA binding, static and immutable but an order of magnitude smaller in RAM). functools/bisect give you nothing here.
What is the most common Python mistake when implementing Trie?
The defaultdict trie is a read-mutating trie. Because defaultdict.__getitem__ inserts the default on a miss, calling search('cats') on a trie that only has 'cat' silently creates the 's' node and every node under the miss path, so a read-only query grows the structure and later prefix enumeration reports phantom branches. Use .get() for every lookup path and reserve __getitem__ for insert. Second Python-specific trap: a recursive delete or DFS blows the 1000-frame default recursion limit on long keys such as URLs or DNA strings. On CPython 3.10 and older, raising sys.setrecursionlimit traded that RecursionError for a genuine C-stack segfault; since 3.11 inlined Python-to-Python calls and 3.12 gave C recursion its own separate limit, a raised limit on a pure-Python DFS is survivable (200k frames measured fine on 3.14). Keep an explicit list as the stack anyway: it is version-independent, and any C-level frame in the recursion still puts the crash back.
How does Trie actually perform in Python?
The big-O hides an interpreter constant: each edge step is a bytecode-level dict lookup plus an attribute load, roughly 40-80 ns on a current CPython (measured 43 ns for children.get(ch) plus the attribute load on 3.14), so a 20-char word costs about a microsecond, not nanoseconds. Memory dominates: an empty dict is 64 bytes plus the node object header, so a naive char-per-node trie over 100k words easily exceeds 100 MB. __slots__ removes 48+ bytes per node; collapsing single-child chains into a radix edge removes most nodes outright. marisa-trie exists precisely because CPython object overhead, not the algorithm, is the cost. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.