Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Lollipop Graph in Python using Networkx module
Next article icon

Introduction to Graphs in Python

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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-Graphs
Introduction to Graphs

Components 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. 

adjacency_mat1-(1)-copy

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) 

Output
Adjacency 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. 

adjacency_list

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) 

Output
Adjacency 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.

ActionAdjacency MatrixAdjacency List
Adding EdgeO(1)O(1)
Removing an edgeO(1)O(N)
InitializingO(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
    • Add and Remove vertex in Adjacency List representation of Graph
    • Add and Remove vertex in Adjacency Matrix representation of Graph
  • Insertion or Deletion of Edges in the graph
    • Add and Remove Edge in Adjacency List representation of a Graph
    • Add and Remove Edge in Adjacency Matrix representation of a 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_graph
Tree vs Graph

read more about - Real-Life Applications, Advantages and Disadvantages of Graph Data Structure


Next Article
Lollipop Graph in Python using Networkx module

B

brijkan3mz4
Improve
Article Tags :
  • Graph
  • Python-DSA
Practice Tags :
  • Graph

Similar Reads

  • Introduction to Graph Data Structure
    Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
    15+ min read
  • Ego graph Using Networkx in Python
    Prerequisite - Graphs, Networkx Basics Ego network is a special type of network consisting of one central node and all other nodes directly connected to it. The central node is known as ego, while the other surrounding nodes directly connected to it are known as alters. Ego networks are mostly used
    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.  Properties of Tutte Graph: It is a cubic polyhedral graph which is evident from the diagram above as it is both cubic an
    2 min read
  • Lollipop Graph in Python using Networkx module
    The lollipop graph consists of 2 components a complete graph called clique and a path graph. More precisely L (m ,n)  is a graph with an m-node complete graph and n-node path graph. L(4,2) Lollipop Graph: Here let's see the properties of this graph: So.no Properties of Lollipop Graph: 1 It is a conn
    3 min read
  • Complete Graph using Networkx in Python
    A complete graph also called a Full Graph it is a graph that has n vertices where the degree of each vertex is n-1. In other words, each vertex is connected with every other vertex. Example: Complete Graph with 6 edges: Properties of Complete Graph: The degree of each vertex is n-1.The total number
    3 min read
  • Bipartite Graphs in Python
    Bipartite graphs are a special type of graph where the nodes can be divided into two distinct sets, with no edges connecting nodes within the same set. Every edge connects a node from the first set to a node in the second set. What is a Bipartite Graph?A graph where the nodes can be divided into two
    5 min read
  • Incidence Matrix in Python
    In graph theory, an incidence matrix is a matrix that shows the relationship between vertices and edges in a graph. This matrix is a fundamental tool used in various applications, including network analysis, circuit design, and computer science. This article will cover the basics of incidence matric
    2 min read
  • Kahn's Algorithm in Python
    Kahn's Algorithm is used for topological sorting of a directed acyclic graph (DAG). The algorithm works by repeatedly removing nodes with no incoming edges and recording them in a topological order. Here's a step-by-step implementation of Kahn's Algorithm in Python. Example: Input: V=6 , E = {{2, 3}
    4 min read
  • Kosaraju's Algorithm in Python
    What is Kosaraju's Algorithm?Kosaraju's Algorithm is a classic graph theory algorithm used to find the Strongly Connected Components (SCCs) in a directed graph. A strongly connected component is a maximal subgraph where every vertex is reachable from every other vertex. Kosaraju's algorithm is effic
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences