Python Snippet

Graph Adjacency List in Python

Difficulty: Medium

An adjacency list represents a graph as 'for each node, the nodes it connects to'. In Python the right shape is `defaultdict(list)`: insertion is one line, traversal is one nested loop, and you do not pay for the V*V matrix. This entry covers building the list, walking it with DFS, and the directed vs undirected detail that bites every newcomer.

Code Snippets
/

Graph Adjacency List in Python

Graph Adjacency List in Python

An adjacency list represents a graph as 'for each node, the nodes it connects to'. In Python the right shape is `defaultdict(list)`: insertion is one line, traversal is one nested loop, and you do not pay for the V*V matrix. This entry covers building the list, walking it with DFS, and the directed vs undirected detail that bites every newcomer.

Python
Medium
3 snippets
graphs
graph-representation
data-structures
py-standard-library

736 views

9

defaultdict(list) removes the boilerplate of 'check if the key exists, create an empty list if not, then append'. For undirected graphs, every edge (u, v) is added twice (u -> v and v -> u) so both endpoints can find each other. The directed=True switch flips that off. The space cost is O(V + E), not O(V^2) like an adjacency matrix, which is why adjacency lists are the default representation for sparse graphs. Sorting the neighbor lists is purely for readable output; in production you keep insertion order so traversal is deterministic.