Graph Data Structure in PythonLast Updated : 4 Mar 2025 A graph is a data structure that represents links or connections between sets of components known as nodes (or vertices). These linkages are known as edges. Graphs are commonly utilized in computer science to speak to a variety of real-world issues, counting social systems, computer frameworks, transportation systems, and others. Types of Graphs1. Directed vs. Undirected Graphs:
2. Weighted vs. Unweighted Graphs:
3. Cyclic vs. Acyclic Graphs:
Representation of Graphs in Python1. Adjacency Matrix
Code: Output: [[0, 0, 0, 1], [1, 1, 1, 0], [0, 1, 0, 0], [1, 0, 1, 1]] Advantages:
Disadvantages:
2. Adjacency List
Using a Dictionary of ListsCode: Output:
{0: [1, 6], 1: [3, 5], 2: [9, 3], 3: [8, 2]}
Using a dictionary of sets (to prevent duplicate edges) Code: Output:
{0: {1, 6}, 1: {3, 5}, 2: {9, 3}, 3: {8, 2}}
Advantages:
Disadvantages:
Graph Traversal Algorithms1. Depth-First Search (DFS)
Code: Output:
{'B', 'A', 'E', 'D', 'G', 'F', 'C'}
Within the new graph:
It will return the list of nodes gone to beginning with node 'A'. Applications:
2. Breadth-First Search (BFS)
Code: Output: ['A', 'B', 'C', 'F'] In this updated graph:
After you run this, the output will appear most briefly, from node 'A' to node 'F', based on this unused graph structure. ConclusionIn Python, graph data structures give a flexible and quick strategy for speaking to and controlling complicated interactions between items. Python includes an assortment of representation strategies, such as adjacency matrices and adjacency lists, as well as solid traversal calculations, such as BFS and DFS, to handle a wide run of graph-related assignments. Understanding and actualizing graphs in Python is basic for effectively tackling a wide range of computational assignments, including modeling networks, finding shortest paths, and executing modern operations such as topological sorting. Next TopicGriptape-for-python |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India