Introduction to Graphs in Python
Last Updated :
03 Mar, 2025
Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E).
Imagine a game of football as a web of connections, where players are the nodes and their interactions on the field are the edges. This web of connections is exactly what a graph data structure represents, and it’s the key to unlocking insights into team performance and player dynamics in sports.
Introduction to GraphsComponents of Graph Data Structure
- Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled.
- Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled.
explore in detail about - Types of Graphs in Data Structures and Algorithms
Representation of Graph Data Structure
There are multiple ways to store a graph, following are the most common representations:
- Adjacency Matrix Representation
- Adjacency List Representation
Adjacency Matrix Representation of Graph Data Structure
In this method, the graph is stored in the form of the 2D matrix where rows and columns denote vertices. Each entry in the matrix represents the weight of the edge between those vertices.
-copy.webp)
Below is the Python implementation of Graph Data Structure represented using Adjacency Matrix:
Python
def add_edge(mat, i, j):
# Add an edge between two vertices
mat[i][j] = 1 # Graph is
mat[j][i] = 1 # Undirected
def display_matrix(mat):
# Display the adjacency matrix
for row in mat:
print(" ".join(map(str, row)))
# Main function to run the program
if __name__ == "__main__":
V = 4 # Number of vertices
mat = [[0] * V for _ in range(V)]
# Add edges to the graph
add_edge(mat, 0, 1)
add_edge(mat, 0, 2)
add_edge(mat, 1, 2)
add_edge(mat, 2, 3)
# Optionally, initialize matrix directly
"""
mat = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
]
"""
# Display adjacency matrix
print("Adjacency Matrix:")
display_matrix(mat)
OutputAdjacency Matrix:
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0
Explore in detail about - Adjacency Matrix Representation
Adjacency List Representation of Graph
This graph is represented as a collection of linked lists. There is an array of pointer which points to the edges connected to that vertex.

Below is the Python implementation of Graph Data Structure represented using Adjacency List:
Python
def add_edge(adj, i, j):
adj[i].append(j)
adj[j].append(i) # Undirected
def display_adj_list(adj):
for i in range(len(adj)):
print(f"{i}: ", end="")
for j in adj[i]:
print(j, end=" ")
print()
# Create a graph with 4 vertices and no edges
V = 4
adj = [[] for _ in range(V)]
# Now add edges one by one
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 2)
add_edge(adj, 2, 3)
print("Adjacency List Representation:")
display_adj_list(adj)
OutputAdjacency List Representation:
0: 1 2
1: 0 2
2: 0 1 3
3: 2
Explore in detail about - Adjacency List Representation
Comparison between Adjacency Matrix and Adjacency List
When the graph contains a large number of edges then it is good to store it as a matrix because only some entries in the matrix will be empty. An algorithm such as Prim’s and Dijkstra adjacency matrix is used to have less complexity.
Action | Adjacency Matrix | Adjacency List |
---|
Adding Edge | O(1) | O(1) |
Removing an edge | O(1) | O(N) |
Initializing | O(N*N) | O(N) |
Basic Operations on Graph Data Structure
Below are the basic operations on the graph:
- Insertion or Deletion of Nodes in the graph
- Insertion or Deletion of Edges in the graph
- Searching in Graph Data Structure- Search an entity in the graph.
- Traversal of Graph Data Structure- Traversing all the nodes in the graph.
Difference between Tree and Graph
Tree is a restricted type of Graph Data Structure, just with some more rules. Every tree will always be a graph but not all graphs will be trees. Linked List, Trees, and Heaps all are special cases of graphs.
Tree vs Graphread more about - Real-Life Applications, Advantages and Disadvantages of Graph Data Structure
Similar Reads
Introduction to Python GIS
Geographic Information Systems (GIS) are powerful tools for managing, analyzing, and visualizing spatial data. Python, a versatile programming language, has emerged as a popular choice for GIS applications due to its extensive libraries and ease of use. This article provides an introduction to Pytho
4 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Introduction to Python for Absolute Beginners
Are you a beginner planning to start your career in the competitive world of Programming? Looking resources for Python as an Absolute Beginner? You are at the perfect place. This Python for Beginners page revolves around Step by Step tutorial for learning Python Programming language from very basics
6 min read
Graph Plotting in Python | Set 1
This series will introduce you to graphing in Python with Matplotlib, which is arguably the most popular graphing and data visualization library for Python.InstallationThe easiest way to install matplotlib is to use pip. Type the following command in the terminal:Â pip install matplotlibOR, you can d
9 min read
Introduction to PyQtGraph Module in Python
PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid appli
4 min read
Python Graph Tools Module
The graph-tools module is a Python package designed for handling directed and undirected graphs, as well as complex networks. It emphasizes performance and provides a wide range of graph algorithms and data structures. It was initially developed for networking researchers who conduct experiments in
2 min read
Grammar of Graphics for Python: An Introduction to Plotline
A grammar of graphics is basically a tool that enables us to describe the components of a given graphic. Basically, what this allows us to see beyond the named graphics, (scatter plot, to name one) and to basically see the underlying statistics behind it. The grammar of graphics was originally intro
6 min read
Introduction to Matplotlib
Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert y
4 min read
Ladder Graph Using Networkx Module in Python
In this article, we are going to see the ladder graph using Python. It is a graph that looks like ladders used commonly with every node attached to two other nodes in a specific manner. We can obtain a ladder graph by joining two-path graphs of n nodes each by each node connected with a correspondin
2 min read
Python NetworkX - Tutte Graph
It is a graph with 46 vertices and 69 edges. It is important because it is an exception to Tait's conjecture which states that every 3-regular polyhedron has a Hamiltonian cycle. Tutte Graph Properties of Tutte Graph: It is a cubic polyhedral graph which is evident from the diagram above as it is b
2 min read