Creating networks in Python
To solve the multitude of problems that can be expressed as network problems, we need a way of creating networks in Python. For this, we will make use of the NetworkX package and the routines and classes it provides to create, manipulate, and analyze networks.
In this recipe, we’ll create an object in Python that represents a network and add nodes and edges to this object.
Getting ready
As we mentioned in the Technical requirements section, we need the NetworkX package to be imported under the nx
alias. We can do this using the following import
statement:
import networkx as nx
How to do it...
Follow these steps to create a Python representation of a simple graph:
- We need to create a new
Graph
object that will store the nodes and edges that constitute the graph:G = nx.Graph()
- Next, we need to add the nodes for the network using the
add_node
method:G.add_node(1)
G.add_node(2)
- To avoid calling this method repetitively...