Adjacency list
- Algorithms course
- Intermediate
- Lesson 50/80
- 4 min
Each vertex stores its neighbours in a list.
Adjacency list
An adjacency list stores each node's neighbors in a list. graph = {'A': ['B', 'C'], 'B': ['A']}.
Memory is O(V + E): each node and edge stored once. Efficient for sparse graphs.
Implemented in Python with a dict + list. Adding a node is O(1), adding an edge is O(1).
Add edge function
When adding an edge, if either node is not in the graph it is first added with an empty list. Then each node is added as a neighbor of the other (in an undirected graph).
add_edge(graph, a, b): graph.setdefault(a, []).append(b) and graph.setdefault(b, []).append(a). Both sides get an append.
In a directed graph only one direction is added; that is, only one side gets an append, the other is skipped.
Practice Add edge
Write add_edge(graph, a, b). Undirected: add to both. Print {'a': ['b'], 'b': ['a']} with g = create_graph(); add_edge(g, 'a', 'b'); print(g).
Starter code
def add_edge(graph, a, b):
# Add undirected edgeSample solution
def create_graph():
return {}
def add_edge(graph, a, b):
# Add undirected edge
graph.setdefault(a, []).append(b)
graph.setdefault(b, []).append(a)
g = create_graph()
add_edge(g, 'a', 'b')
print(g)Expected output
{'a': ['b'], 'b': ['a']}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add edge
graph[a].append(____)
graph[a].append(b)
Explanation: b is right.
2 Adjacency list: match the terms
| Term | Meaning |
|---|---|
Adjacency list |
O(V+E) |
Add edge |
O(1) |
Sparse graph |
Efficient |
Undirected |
Both ways |
3 What is the adjacency list memory?
- O(V^2)
- O(E)
- O(V + E) Correct answer
- O(V)
Explanation: O(V + E)