NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms and draw networks.
Installation of the package:
pip install networkx
Creating Nodes
Add one node at a time:
G.add_node(1)
Add a list of nodes:
G.add_nodes_from([2,3])
Let us create nodes in the graph G. After adding nodes 1, 2, 3, 4, 7, 9

Creating Edges:
Adding one edge at a time:
G.add_edge(1,2)
G.add_edge(3,1)
G.add_edge(2,4)
G.add_edge(4,1)
G.add_edge(9,1)
Adding a list of edges:
G.add_edges_from([(1,2),(1,3)])
After adding edges (1,2), (3,1), (2,4), (4,1), (9,1), (1,7), (2,9)

Removing Nodes and Edges:
One can demolish the graph using any of these functions:
Graph.remove_node(), Graph.remove_nodes_from(),
Graph.remove_edge() and Graph.remove_edges_from()
After removing node 3

After removing edge (1,2)
Python3
import networkx
G = networkx.Graph()
G.add_node( 1 )
G.add_node( 2 )
G.add_node( 3 )
G.add_node( 4 )
G.add_node( 7 )
G.add_node( 9 )
G.add_edge( 1 , 2 )
G.add_edge( 3 , 1 )
G.add_edge( 2 , 4 )
G.add_edge( 4 , 1 )
G.add_edge( 9 , 1 )
G.add_edge( 1 , 7 )
G.add_edge( 2 , 9 )
node_list = G.nodes()
print ( "#1" )
print (node_list)
edge_list = G.edges()
print ( "#2" )
print (edge_list)
G.remove_node( 3 )
node_list = G.nodes()
print ( "#3" )
print (node_list)
G.remove_edge( 1 , 2 )
edge_list = G.edges()
print ( "#4" )
print (edge_list)
n = G.number_of_nodes()
print ( "#5" )
print (n)
m = G.number_of_edges()
print ( "#6" )
print (m)
d = G.degree( 2 )
print ( "#7" )
print (d)
neighbor_list = G.neighbors( 2 )
print ( "#8" )
print (neighbor_list)
G.clear()
|
Output:
#1
[1, 2, 3, 4, 7, 9]
#2
[(1, 9), (1, 2), (1, 3), (1, 4), (1, 7), (2, 4), (2, 9)]
#3
[1, 2, 4, 7, 9]
#4
[(1, 9), (1, 4), (1, 7), (2, 4), (2, 9)]
#5
5
#6
5
#7
2
#8
[4, 9]
In the next post, we’ll be discussing how to create weighted graphs, directed graphs, multi graphs. How to draw graphs. In later posts we’ll see how to use inbuilt functions like Depth first search aka dfs, breadth first search aka BFS, dijkstra’s shortest path algorithm.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
11 Jul, 2022
Like Article
Save Article