PYTHON

Represent a Graph Using an Adjacency List

Learn to implement a simple graph data structure using an adjacency list in Python, useful for modeling connections like social networks, routes, or dependencies in web applications.

class Graph:
    def __init__(self):
        self.graph = {} # Dictionary to store adjacency list: {node: [neighbors]}

    def add_edge(self, u, v, bidirectional=True):
        """Adds an edge between nodes u and v."""
        if u not in self.graph:
            self.graph[u] = []
        if v not in self.graph:
            self.graph[v] = []

        self.graph[u].append(v)
        if bidirectional:
            self.graph[v].append(u)

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

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

# Example usage:
g = Graph()
g.add_edge("A", "B")
g.add_edge("A", "C")
g.add_edge("B", "D")
g.add_edge("C", "E")
g.add_edge("D", "E", bidirectional=False) # Directed edge from D to E

print("Graph representation (Adjacency List):", g.graph)
print("Neighbors of A:", g.get_neighbors("A"))
print("Neighbors of D:", g.get_neighbors("D"))
print("Neighbors of F (non-existent):", g.get_neighbors("F"))
How it works: This snippet demonstrates how to represent a graph using an adjacency list, a common and efficient way to store graph data. The `Graph` class uses a dictionary where each key is a node, and its value is a list of its neighboring nodes. The `add_edge` method allows adding both bidirectional (default) and unidirectional edges, while `get_neighbors` retrieves connected nodes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs