Huffman Encoding 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
- ✓Huffman Encoding runs in O(n log n) time and O(n) space, in Python as in every other language.
- ✓heapq is a binary min-heap over a plain list, there is no separate heap object, just heapq.heappush/heappop operating on a list you own.
- ✓Push (weight, order, node) three-tuples, where order comes from a shared itertools.count(), never compare node objects directly, and never rely on Python's default equality/ordering for your tree-node class.
- ✓The Python trap: Without the counter tie-breaker, two equal-weight tuples fall through to comparing the Node objects, and if Node does not define __lt__ that raises TypeError: '<' not supported between instances of 'Node' and 'Node' at runtime, only when two frequencies happen to tie, code that looks correct in every test until the input distribution changes.
- ✓Every heappush/heappop is O(log n) over a Python-level list of tuples, and building the initial n-symbol heap is O(n).
What Huffman Encoding actually is
Huffman Encoding in Python: what you actually reach for
Python implementation
import heapq
from collections import Counter
from itertools import count
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Node:
weight: int
symbol: Optional[str] = None
left: Optional["Node"] = None
right: Optional["Node"] = None
def build_tree(text: str) -> Node:
freqs = Counter(text)
tiebreak = count() # decides ties so Node never needs __lt__
heap = [(w, next(tiebreak), Node(weight=w, symbol=s)) for s, w in freqs.items()]
heapq.heapify(heap)
if len(heap) == 1:
_, _, only = heap[0]
return Node(weight=only.weight, left=only, right=Node(weight=0, symbol="\0"))
while len(heap) > 1:
w1, _, n1 = heapq.heappop(heap)
w2, _, n2 = heapq.heappop(heap)
parent = Node(weight=w1 + w2, left=n1, right=n2)
heapq.heappush(heap, (parent.weight, next(tiebreak), parent))
return heap[0][2]
def build_codes(node: Node, prefix: str = "", table: dict[str, str] | None = None) -> dict[str, str]:
table = {} if table is None else table
if node.symbol is not None:
table[node.symbol] = prefix or "0"
return table
build_codes(node.left, prefix + "0", table)
build_codes(node.right, prefix + "1", table)
return tableThink 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(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Huffman Encoding?
heapq is a binary min-heap over a plain list, there is no separate heap object, just heapq.heappush/heappop operating on a list you own. It has no decrease-key and no built-in tie-breaker, so pushing (weight, node) tuples directly fails the moment two weights are equal and Python tries to compare the second tuple element to break the tie. itertools.count() supplies a monotonically increasing counter used as that tie-breaker. collections.Counter builds the frequency table in one pass over the input.
What is the most common Python mistake when implementing Huffman Encoding?
Without the counter tie-breaker, two equal-weight tuples fall through to comparing the Node objects, and if Node does not define __lt__ that raises TypeError: '<' not supported between instances of 'Node' and 'Node' at runtime, only when two frequencies happen to tie, code that looks correct in every test until the input distribution changes. The second common bug is building the code table with a naive recursive walk that never terminates on a single-symbol input, because a tree with one leaf and no root split needs an explicit special case (assign it code '0'), which the general left/right recursion silently skips.
How does Huffman Encoding actually perform in Python?
Every heappush/heappop is O(log n) over a Python-level list of tuples, and building the initial n-symbol heap is O(n). The n-1 merges each do O(log n) work, giving the standard O(n log n) total, but the constant factor is real: each comparison walks a 3-tuple and Python's heap operations are pure-Python C loops around list swaps, not vectorized. For an alphabet of at most a few hundred symbols (the normal case: byte-level Huffman never exceeds 256 leaves) this is a rounding error regardless. Time complexity is O(n log n) and space is O(n).
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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out 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.