Python Graphs


Graphs are one of the most important data structures in programming. They help represent connections and relationships between values. You can think of a graph as a set of points and the links between them. These points are called nodes and the connections are called edges. Graphs are used everywhere: social networks, maps, routes, recommendations, networks and problem solving algorithms. Learning how graphs work gives you a strong foundation for handling complex tasks in Python.

In this tutorial, you will learn what a graph is, the difference between directed and undirected graphs, how to represent graphs in Python, how to work with adjacency lists, adjacency matrices, weighted graphs, graph traversal methods like BFS and DFS and real examples that show how graphs appear in real life. You will also see full Python code for building and exploring graphs step by step.

What Is a Graph?

A graph is a structure that contains:

  • A set of nodes

  • A set of edges connecting the nodes

A simple example is:

A -- B -- C
|         |
D ------- E

Each line between nodes represents a connection.

Graphs don't follow a strict hierarchy like trees. They can have cycles, multiple paths, loops and many kinds of structures depending on the problem.

Directed vs Undirected Graphs

Graphs come in two main types.

Undirected Graph

Edges do not have direction.
If A connects to B, then B also connects to A.

This is common in social networks (friendships).

Directed Graph

Edges have direction.
A connection from A to B does not mean B connects to A.

This appears in websites linking to each other, traffic routes and recommendations.

Weighted vs Unweighted Graphs

Sometimes edges have values associated with them.

Weighted Graph

Each edge has a weight.
This can represent distance, time, cost or priority.

Example:
Finding the shortest route on a map.

Unweighted Graph

All edges are equal.
Used when only structure matters, not the cost.

Common Ways to Represent Graphs in Python

There are two popular methods.

Adjacency List

Each node stores a list of its neighbors.

Example:

graph = {
    "A": ["B", "D"],
    "B": ["A", "C"],
    "C": ["B", "E"],
    "D": ["A", "E"],
    "E": ["D", "C"]
}

This is the most common way because it saves memory and is easy to work with.

Adjacency Matrix

A grid of 0s and 1s shows which nodes connect.

Example for A, B, C:

    A B C
A [ 0 1 0 ]
B [ 1 0 1 ]
C [ 0 1 0 ]

This uses more memory but is helpful for dense graphs.

Creating a Graph Class in Python

Here is a simple class for building an adjacency list graph:

class Graph:
    def __init__(self):
        self.graph = {}

    def add_node(self, value):
        if value not in self.graph:
            self.graph[value] = []

    def add_edge(self, a, b):
        self.add_node(a)
        self.add_node(b)
        self.graph[a].append(b)
        self.graph[b].append(a)

This creates an undirected graph with easy node and edge insertion.

Working With Directed Graphs

For a directed graph, remove the second connection:

def add_directed_edge(self, a, b):
    self.add_node(a)
    self.add_node(b)
    self.graph[a].append(b)

Now edges go only one way.

Breadth First Search (BFS)

BFS visits nodes level by level.
You start from a node and explore all its neighbors before moving deeper.

Example BFS code:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node)
            visited.add(node)
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)

BFS is used in:

  • Shortest path in unweighted graphs

  • Finding levels in social networks

  • Spread simulation (fire, water, information)

Depth First Search (DFS)

DFS goes deep before exploring siblings.

Example DFS code:

def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()

    if node not in visited:
        print(node)
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)

DFS is used in:

  • Backtracking

  • Pathfinding

  • Cycle detection

  • Solving puzzles like mazes

Weighted Graph Representation

Weighted graphs store pairs of values:

weighted_graph = {
    "A": [("B", 4), ("D", 2)],
    "B": [("A", 4), ("C", 3)],
    "C": [("B", 3), ("E", 5)],
    "D": [("A", 2), ("E", 1)],
    "E": [("D", 1), ("C", 5)]
}

Each edge has a number representing cost or distance.

Real-Life Uses of Graphs

Maps and Navigation

Cities are nodes, roads are edges.
Graphs help find shortest paths and travel routes.

Social Media

Users are nodes.
Friendships or followers are edges.
Used for recommendations and connections.

Search Engines

Webpages are nodes.
Links are directed edges.
Used to rank and crawl pages.

Network Routing

Graph algorithms help send packets across the internet.

Recommendation Systems

Items and users form connections.
Edges show similarity or behavior patterns.

Example: Building and Traversing a Graph in Python

g = Graph()
g.add_edge("A", "B")
g.add_edge("A", "D")
g.add_edge("B", "C")
g.add_edge("C", "E")
g.add_edge("D", "E")

print("BFS:")
bfs(g.graph, "A")

print("DFS:")
dfs(g.graph, "A")

This creates a small graph and prints nodes in BFS and DFS order.

More Practical Examples

Example 1: Add a new node

g.add_node("F")

Example 2: Connect nodes

g.add_edge("E", "F")

Example 3: Directed edge

g.add_directed_edge("F", "A")

Example 4: Weighted edge structure

("A", "B", 10)

Example 5: List neighbors

print(g.graph["A"])

Example 6: BFS from another start

bfs(g.graph, "C")

Example 7: DFS from leaf node

dfs(g.graph, "E")

Example 8: Check if path exists (BFS based)

Loop until you find the target.

Example 9: Count connected components

Use DFS to check reachability.

Example 10: Remove edge

Remove the value from the list manually.

Summary of the Tutorial

A graph is a structure that represents connections between nodes. It can be directed, undirected, weighted or unweighted depending on the problem. In this tutorial, you learned how graphs work, how to build them using adjacency lists, how to work with BFS and DFS, how to store weighted edges and how these structures appear in real systems like maps, networks and recommendations. Graphs are a key part of data structures and understanding them opens up many important algorithms and problem-solving patterns.


Practice Questions

Q1. Write a Python program to create an undirected graph with 5 nodes using an adjacency list.

Q2. Write a Python program to implement a function to add new vertices to the graph.

Q3. Write a Python program to traverse the graph using Depth-First Search (DFS).

Q4. Write a Python program to traverse the graph using Breadth-First Search (BFS).

Q5. Write a Python program to count the number of connections (edges) for a given node.

Q6. Write a Python program to check if two nodes are connected directly.

Q7. Write a Python program to list all paths between two nodes using recursion or DFS.

Q8. Write a Python program to convert an adjacency list into an adjacency matrix.

Q9. Write a Python program to mark and print all visited nodes during a DFS traversal.

Q10. Write a Python program to create a weighted undirected graph using a dictionary of dictionaries or a tuple-based structure.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top