PYTHON

Representing Graphs Using an Adjacency List in Python

Learn to represent graphs efficiently using an adjacency list in Python, a fundamental data structure for graph algorithms like BFS and DFS.

from collections import defaultdict

class Graph:
    def __init__(self, directed=False):
        self._graph = defaultdict(list)
        self._directed = directed

    def add_edge(self, u, v):
        """Adds an edge from node u to node v."""
        self._graph[u].append(v)
        if not self._directed:
            self._graph[v].append(u) # For undirected graphs, add edge in reverse too

    def get_neighbors(self, node):
        """Returns a list of neighbors for a given node."""
        return self._graph[node]

    def get_nodes(self):
        """Returns a list of all nodes in the graph."""
        return list(self._graph.keys())

    def __str__(self):
        graph_str = "Graph adjacency list:
"
        for node in sorted(self._graph.keys()):
            graph_str += f"  {node}: {self._graph[node]}
"
        return graph_str

# Example Usage - Undirected Graph:
undirected_graph = Graph(directed=False)
undirected_graph.add_edge('A', 'B')
undirected_graph.add_edge('A', 'C')
undirected_graph.add_edge('B', 'D')
undirected_graph.add_edge('C', 'E')
undirected_graph.add_edge('D', 'E')
print("
--- Undirected Graph ---")
print(undirected_graph)
# Expected output:
# A: ['B', 'C']
# B: ['A', 'D']
# C: ['A', 'E']
# D: ['B', 'E']
# E: ['C', 'D']

# Example Usage - Directed Graph:
directed_graph = Graph(directed=True)
directed_graph.add_edge('X', 'Y')
directed_graph.add_edge('X', 'Z')
directed_graph.add_edge('Z', 'Y')
print("
--- Directed Graph ---")
print(directed_graph)
# Expected output:
# X: ['Y', 'Z']
# Z: ['Y']
How it works: This snippet demonstrates how to represent graphs using an adjacency list in Python. It uses a `defaultdict(list)` where each key is a node, and its corresponding value is a list of nodes adjacent to it. This representation is efficient for sparse graphs (graphs with relatively few edges) because it only stores existing connections. It supports both directed and undirected graphs by conditionally adding reverse edges. Adjacency lists are a cornerstone for implementing graph traversal algorithms like Breadth-First Search (BFS) and Depth-First Search (DFS).

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs