Sub topic 6
Self-loops and parallel edges
This chapter assumes you know what a graph is, the difference between directed and undirected edges, and the definition of degree. It also assumes you can read basic Python.
Two special kinds of edge
A self-loop is an edge that starts and ends at the same vertex, such as ("B", "B"). A page that links to itself is one example.
Parallel edges are two or more edges that join the same pair of vertices (in a directed graph, the same ordered pair). Two separate flights from A to B are one example.
A simple graph has neither. A multigraph allows parallel edges, and in most definitions it allows self-loops too. Many textbooks use "pseudograph" for a multigraph that allows loops. Whether you need them depends on what an edge means in your problem.
Degree with loops
In an undirected graph, a self-loop adds 2 to its vertex's degree, because both ends of the edge touch that vertex. In the diagram, B has degree 1 + 1 + 2 + 1 = 5. This convention keeps the handshake rule true: the sum of all degrees equals twice the number of edges.
In a directed graph, a self-loop adds 1 to the in-degree and 1 to the out-degree.
How each representation handles them
- Edge list. It handles both naturally. Parallel edges are repeated pairs, and a loop is a pair with equal endpoints. You can also attach an ID or weight to each entry to tell parallel edges apart.
- Adjacency list. Parallel edges appear as repeated neighbors. For an undirected loop, appending both directions puts the vertex in its own list twice. That matches the degree rule.
- Adjacency matrix. A 0/1 entry cannot record two edges between the same pair. Store a count instead. A loop appears on the diagonal.
from collections import defaultdict
edges = [("A", "B"), ("A", "B"), ("B", "B"), ("B", "C")]
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u) # for a loop, this appends the vertex twice
print(graph["A"]) # ['B', 'B']
print(graph["B"]) # ['A', 'A', 'B', 'B', 'C']
print(len(graph["B"])) # 5, the degree of B
nodes = ["A", "B", "C"]
index = {name: i for i, name in enumerate(nodes)}
matrix = [[0] * len(nodes) for _ in nodes]
for u, v in edges:
matrix[index[u]][index[v]] += 1
matrix[index[v]][index[u]] += 1 # a loop adds 2 on the diagonal
for row in matrix:
print(row, sum(row))
# [0, 2, 0] 2
# [2, 2, 1] 5
# [0, 1, 0] 1Each row sum equals that vertex's degree. This holds only because the loop was counted twice.
When to forbid them
Many algorithms assume a simple graph. Some examples:
- A shortest-path search never benefits from a loop with a non-negative weight, so it can skip loops.
- Among parallel edges with different weights, only the cheapest matters for shortest paths.
- Counting problems, such as the number of walks of a given length, need the multiplicities. Dropping parallel edges changes the answer.
If your data might contain duplicates, decide early. You can reject them, merge them (keep the minimum weight, or keep a count), or keep them as separate edges. A dictionary of dictionaries merges parallel edges by default, because a second assignment to wgraph[u][v] overwrites the first. That is useful in some cases and a silent bug in others.
Looking ahead
An edge list with IDs can already tell parallel edges apart, but the adjacency matrix cannot. The incidence matrix, covered later, gives each edge its own column. That makes it a natural fit for multigraphs.
Exercise
An undirected graph has edges [("X", "Y"), ("X", "Y"), ("Y", "Y")]. Using the convention that a loop adds 2 to degree, what are the degrees of X and Y, and what is the sum of degrees compared with the number of edges?
Show answer
X has degree 2 (two parallel edges to Y). Y has degree 2 + 2 = 4 (the two parallel edges plus the loop counted twice). The sum is 6, which is twice the 3 edges, so the handshake rule holds.