python logo

python graph


Python hosting: Host, run, and code Python in the cloud!

Graphs are fundamental structures in mathematics and computer science that represent the relationship between entities. In essence, a graph is made up of nodes, and the connections between these nodes are termed as edges. Depending on the nature of the connections, a graph can either be directed (with arrows indicating direction) or undirected. Furthermore, these edges might also carry information such as distance or weight, which provides more insights into the relationships between nodes.

Graph illustration showing default and directed graphs

If you’re using Python for your projects and are looking to work with graphs, you might find that Python doesn’t have a built-in graph data structure. However, there are two primary ways to work with graphs in Python:

  1. Implementing graphs from scratch.
  2. Leveraging the networkx module.

Recommended Reading: Python Programming Bootcamp: Go from zero to hero

Implementing Graphs in Python

Below is a simple representation of a directed graph in Python using dictionaries:

1
2
3
4
5
6
7
8
#!/usr/bin/env python

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

print(graph)

This code represents a directed graph where node ‘A’ is connected to nodes ‘B’ and ‘C’, and so forth.

Working with Graphs using networkx

The networkx module in Python provides comprehensive tools and functions to create and manipulate graphs. Here’s a basic demonstration of how to create a graph using this module:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
import networkx as nx

G = nx.Graph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_edge("A", "B")
G.add_edge("B", "C")
G.add_edge("C", "A")

print("Nodes:", G.nodes())
print("Edges:", G.edges())

When you run the above code, the output will display the nodes and edges of the graph, which are:

1
2
Nodes: ['A', 'C', 'B']
Edges: [('A', 'C'), ('A', 'B'), ('C', 'B')]

To continue exploring Python modules, you can head Back or move to the Next topic.






Leave a Reply:




Al-Amin Mon, 28 Dec 2015

import networkx as nx
dosen't work syntaxerror

Frank Mon, 28 Dec 2015

Install the networkx module using: pip install networkx

Carl Wainwright Mon, 29 Aug 2016

You will need to install virtualenv on OSX otherwise you will have trouble installing networkx module.