Topological Sort 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
- ✓Topological Sort runs in O(V+E) time and O(V) space, in Python as in every other language.
- ✓graphlib.TopologicalSorter (stdlib since 3.9) is the real answer: build it with a dict mapping each node to its predecessors, call .static_order() for a full ordering, or drive it incrementally with .prepare() / .get_ready() / .done() when independent nodes should be processed in parallel rather than one at a time.
- ✓Reach for graphlib.TopologicalSorter first, it already handles cycle detection (CycleError), incremental and parallel processing, and is maintained as part of the language, so hand-rolling Kahn's algorithm in application code is something a reviewer will ask you to justify.
- ✓The Python trap: A Kahn's-algorithm implementation that uses a plain list and list.pop(0) for the queue is a correctness-neutral but real complexity bug: list.pop(0) is O(n) because every remaining element shifts down one slot, so an implementation that looks like textbook O(V+E) is actually O(V^2) once you account for the queue operations, nothing raises an error, it just gets quietly slower as the graph grows, exactly the kind of bug that passes every small test fixture.
- ✓O(V+E) with collections.deque, since popleft() and append() are both O(1); graphlib.TopologicalSorter is implemented with CPython-level optimizations for the common path and typically outperforms an equivalent hand-rolled pure-Python Kahn's algorithm on large graphs even though both share the same asymptotic bound.
What Topological Sort actually is
Topological Sort in Python: what you actually reach for
Python implementation
import graphlib
def topo_order(graph: dict[str, list[str]]) -> list[str]:
# graphlib expects {node: predecessors}, so invert the adjacency direction
predecessors: dict[str, set[str]] = {n: set() for n in graph}
for node, deps in graph.items():
for dep in deps:
predecessors.setdefault(dep, set())
predecessors[dep].add(node)
try:
return list(graphlib.TopologicalSorter(predecessors).static_order())
except graphlib.CycleError as e:
raise ValueError(f"not a DAG, cycle involves: {e.args[1]}") from e
# hand-rolled Kahn's, for when you need the O(1) queue behavior explicit:
from collections import deque, defaultdict
def kahn(graph: dict[str, list[str]]) -> list[str]:
indegree: dict[str, int] = defaultdict(int)
for node in graph:
indegree.setdefault(node, 0)
for nxt in graph[node]:
indegree[nxt] += 1
queue = deque(n for n, d in indegree.items() if d == 0) # deque: O(1) popleft
order: list[str] = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph.get(node, ()):
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
if len(order) != len(indegree):
raise ValueError("not a DAG")
return orderThink 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(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Topological Sort?
graphlib.TopologicalSorter (stdlib since 3.9) is the real answer: build it with a dict mapping each node to its predecessors, call .static_order() for a full ordering, or drive it incrementally with .prepare() / .get_ready() / .done() when independent nodes should be processed in parallel rather than one at a time. For a hand-rolled Kahn's algorithm, collections.deque supplies the O(1)-at-both-ends queue.
What is the most common Python mistake when implementing Topological Sort?
A Kahn's-algorithm implementation that uses a plain list and list.pop(0) for the queue is a correctness-neutral but real complexity bug: list.pop(0) is O(n) because every remaining element shifts down one slot, so an implementation that looks like textbook O(V+E) is actually O(V^2) once you account for the queue operations, nothing raises an error, it just gets quietly slower as the graph grows, exactly the kind of bug that passes every small test fixture.
How does Topological Sort actually perform in Python?
O(V+E) with collections.deque, since popleft() and append() are both O(1); graphlib.TopologicalSorter is implemented with CPython-level optimizations for the common path and typically outperforms an equivalent hand-rolled pure-Python Kahn's algorithm on large graphs even though both share the same asymptotic bound. The list.pop(0) version is the one case here where the real constant is not "a small constant", it is O(n) per removal, and it is worth checking which one is actually running before trusting a complexity claim in code review. Time complexity is O(V+E) and space is O(V).
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 trialIf you are a student, see what Devin offers students for free 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.