How to Implement Graph in Python: A Clear and Engaging Guide

Graphs are everywhere. From your social media network to the map application you use, they power the digital world. Understanding how to implement graph in Python is a fundamental skill for any programmer diving into data structures.

This guide will walk you through two simple and effective methods. You will learn how to represent connections and relationships in your code with ease. Let’s break down the process of how to implement a graph in Python.

Method 1: The Adjacency List (Using a Dictionary)

The adjacency list is a popular and efficient way to implement a graph. It uses a collection of lists or dictionaries to store each node’s neighbors. It’s memory-friendly for sparse graphs (graphs with few connections).

Think of it like a guest list for a party where each person has a list of who they came with.

Here is the basic structure:

graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A'],
    'D': ['B']
}

In this code, node ‘A’ is connected to nodes ‘B’ and ‘C’. Node ‘B’ is connected to ‘A’ and ‘D’, and so on. This represents an undirected graph.

Let’s build a class to make this more powerful.

class Graph:
    def __init__(self):
        self.adj_list = {}

    def add_vertex(self, vertex):
        if vertex not in self.adj_list:
            self.adj_list[vertex] = []
            return True
        return False

    def add_edge(self, v1, v2):
        if v1 in self.adj_list and v2 in self.adj_list:
            self.adj_list[v1].append(v2)
            self.adj_list[v2].append(v1)  # Remove for a directed graph
            return True
        return False

    def print_graph(self):
        for vertex, edges in self.adj_list.items():
            print(f"{vertex}: {edges}")

# Let's use our Graph class
my_graph = Graph()
my_graph.add_vertex('A')
my_graph.add_vertex('B')
my_graph.add_vertex('C')
my_graph.add_vertex('D')

my_graph.add_edge('A', 'B')
my_graph.add_edge('A', 'C')
my_graph.add_edge('B', 'D')

my_graph.print_graph()

Output:
text
A: ['B', 'C']
B: ['A', 'D']
C: ['A']
D: ['B']

This class gives you control to add vertices and edges dynamically.

Method 2: The Adjacency Matrix (Using a 2D List)

An adjacency matrix uses a 2D array (a list of lists in Python) to represent the graph. A value 1 (or a weight) at matrix[i][j] indicates an edge from node i to node j. It’s great for dense graphs but uses more memory.

Imagine a grid where the row and column labels are your nodes. A mark in a cell shows a connection between them.

Here’s how to implement this graph in Python with a matrix:

class Graph:
    def __init__(self, num_vertices):
        self.num_vertices = num_vertices
        self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]
        self.vertices = {}  # To map vertex names to indices
        self.vertices_list = [0] * num_vertices  # To map indices to vertex names

    def add_vertex(self, vertex, index):
        if 0 <= index < self.num_vertices:
            self.vertices[vertex] = index
            self.vertices_list[index] = vertex

    def add_edge(self, v1, v2):
        i1 = self.vertices.get(v1)
        i2 = self.vertices.get(v2)
        if i1 is not None and i2 is not None:
            # For an undirected graph
            self.adj_matrix[i1][i2] = 1
            self.adj_matrix[i2][i1] = 1  # Remove this line for a directed graph

    def print_matrix(self):
        print("  ", end="")
        for vertex in self.vertices:
            print(vertex, end=" ")
        print()
        for i, row in enumerate(self.adj_matrix):
            print(self.vertices_list[i], end=" ")
            for val in row:
                print(val, end=" ")
            print()

# Example usage
num_vertices = 4
my_graph = Graph(num_vertices)

# Add vertices with an index position
my_graph.add_vertex('A', 0)
my_graph.add_vertex('B', 1)
my_graph.add_vertex('C', 2)
my_graph.add_vertex('D', 3)

# Add edges
my_graph.add_edge('A', 'B')
my_graph.add_edge('A', 'C')
my_graph.add_edge('B', 'D')

my_graph.print_matrix()

Output:
text
 A B C D 
A 0 1 1 0 
B 1 0 0 1 
C 1 0 0 0 
D 0 1 0 0

The matrix shows a 1 where a connection exists, providing a clear visual representation.

Which Method Should You Choose?

Your choice depends on the problem.

  • Use an Adjacency List when your graph has few edges. It is space-efficient and faster to iterate over a node’s neighbors.
  • Use an Adjacency Matrix when your graph has many edges or you need to quickly check if a specific connection exists (e.g., is_connected(i, j)).

You now know how to implement graph in Python using two core methods. Start with the adjacency list for most problems—it’s intuitive and efficient. Practice building graphs and then explore amazing algorithms like Breadth-First Search (BFS) and Depth-First Search (DFS) to traverse them! Happy coding!

Dive deeper! Explore these related articles to master the fundamentals:
How to Solve Two Sum Problem: The Ultimate Guide
Data Science in Finance: What you need to know
Data Science Vs Data Analytics: The Battle For The Best Career In Tech
Why DSA Matters: The Secret Ingredient in Successful Coding Projects
Understanding Data Structures: A Comprehensive Guide

Index
Scroll to Top