01 / 20

Graph Representation
Adjacency Lists in Python

Learn how to represent graphs using dictionaries of lists and sets in Python: the most flexible and widely-used approach in coding interviews and real-world applications.

Python

What is a Graph?

A graph is a data structure made of two components: nodes (also called vertices) connected by edges. Graphs model relationships: friendships on social media, roads between cities, dependencies between tasks.

A B C D E 5 nodes, 5 edges

Key Vocabulary

Vertex / Node
A single entity in the graph, like a person or city.
Edge
A connection between two vertices, like a road or friendship.
Neighbor
A vertex directly connected to another by an edge.
Undirected
Edges go both ways: if A connects to B, then B connects to A.
Directed
Edges have direction: A → B does not mean B → A.

Why Representation Matters

A graph drawn on paper is intuitive, but computers need a structured format to store and traverse it. The way you represent a graph determines how fast you can:

1
Check if an edge exists between two nodes
2
Find all neighbors of a given node
3
Add or remove nodes and edges dynamically
4
Run algorithms like BFS, DFS, Dijkstra efficiently

The Adjacency List: Core Idea

An adjacency list maps each vertex to a collection of its neighbors. In Python, we use a dictionary where each key is a node and each value is a list or set of neighbors.

0 1 2 3 → graph = { 0 : [ 1, 2 ], 1 : [ 0, 2 ], 2 : [ 0, 1, 3 ], 3 : [ 2 ], } dict of lists

Lists vs Sets as Values

The neighbors can be stored as a list or a set. Each choice has trade-offs:

dict of lists dict of sets
Edge lookup \( O(n) \) : scan list \( O(1) \) average
Add edge \( O(1) \) : append \( O(1) \) : add
Remove edge \( O(n) \) : find + remove \( O(1) \) : discard
Duplicate edges Possible (must guard) Automatically prevented
Preserves order Yes No

Building an Undirected Graph

For an undirected graph, every edge is bidirectional. When you add edge (u, v), add v to u's list and u to v's list.

# Build an undirected graph from an edge list def build_undirected(edges): graph = {} for u, v in edges: if u not in graph: graph[u] = [] if v not in graph: graph[v] = [] graph[u].append(v) graph[v].append(u) return graph

Building a Directed Graph

For a directed graph, edge (u, v) means u → v only. We add v to u's list but not the reverse.

# Build a directed graph from an edge list def build_directed(edges): graph = {} for u, v in edges: if u not in graph: graph[u] = [] if v not in graph: graph[v] = [] graph[u].append(v) return graph

Cleaner Code with defaultdict

Python's collections.defaultdict auto-creates missing keys, eliminating the need for explicit if key not in checks.

from collections import defaultdict # Undirected graph with defaultdict graph = defaultdict(list) edges = [(0,1), (0,2), (1,2), (2,3)] for u, v in edges: graph[u].append(v) graph[v].append(u) # With sets instead: graph_set = defaultdict(set) for u, v in edges: graph_set[u].add(v) graph_set[v].add(u)

Step-by-Step Approach

1
Choose your container: dict of list or set. Use defaultdict for convenience.
2
Identify edge type: directed or undirected? This determines whether you add one or two entries per edge.
3
Iterate over edges: for each (u, v), append/add v to graph[u]. If undirected, also add u to graph[v].
4
Handle isolated nodes: ensure every node appears as a key, even with an empty neighbor list.
5
Query the graph: graph[node] returns all neighbors. Iterate to run BFS/DFS.

Example 1: Simple Undirected Graph

A B C { "A": ["B","C"], "B": ["A","C"], "C": ["A","B"], }
graph = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B"]} # Neighbors of A: print(graph["A"]) # ['B', 'C']

Example 2: Directed Graph

1 2 3 { 1: [2, 3], 2: [3], 3: [], } node 3 has no outgoing edges
from collections import defaultdict graph = defaultdict(list) edges = [(1,2), (1,3), (2,3)] for u, v in edges: graph[u].append(v) # one direction only! graph[v] # ensure v exists as a key

Example 3: Larger Graph with Sets

0 1 2 3 4 graph = { 0: {1, 2, 3}, 1: {0, 2}, 2: {0, 1, 3}, 3: {0, 2, 4}, 4: {3}, } defaultdict(set)

Common Operations

# Given: graph = {0: [1,2], 1: [0,2], 2: [0,1,3], 3: [2]} # 1. Get all neighbors of node 2 neighbors = graph[2] # [0, 1, 3] # 2. Check if edge (1, 3) exists (list version) has_edge = 3 in graph[1] # False # 3. Count neighbors (degree of node) degree = len(graph[2]) # 3 # 4. Add a new edge (2, 4) to undirected graph graph[2].append(4) graph[4] = [2] # 5. Iterate over all nodes and their neighbors for node, nbrs in graph.items(): print(node, "→", nbrs)

Common Mistakes

✕ One-Way Undirected
Adding v to graph[u] but forgetting to add u to graph[v] for undirected graphs.
✕ Missing Nodes
Not initializing isolated nodes as keys. If node 5 has no edges, graph[5] should still exist as [].
✕ Duplicate Edges in Lists
Appending the same neighbor twice when using lists. Use sets or check before appending.

Representation Summary

Adjacency List Adjacency Matrix Edge List
Space \( O(V + E) \) \( O(V^2) \) \( O(E) \)
Edge check \( O(\text{deg}) \) or \( O(1) \) \( O(1) \) \( O(E) \)
All neighbors \( O(\text{deg}) \) \( O(V) \) \( O(E) \)
Add edge \( O(1) \) \( O(1) \) \( O(1) \)
Best for Sparse graphs Dense graphs Simple storage

Question 1 of 5

Given an undirected graph with edge (A, B), which adjacency list is correct?

Question 2 of 5

What is the main advantage of using defaultdict(set) over defaultdict(list) for an adjacency list?

Question 3 of 5

Given this directed graph code, what does graph[2] return?

Question 4 of 5

What is the space complexity of an adjacency list for a graph with \( V \) vertices and \( E \) edges?

Question 5 of 5

You have an undirected graph stored as a dict of lists. How do you find the degree of node "X"?