Open In App

NetworkX : Python software package for study of complex networks

Last Updated : 11 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

NetworkX is a Python library for creating, analyzing and visualizing complex networks. It models real-world systems as graphs, where nodes represent entities and edges represent relationships. The library supports loading, storing and generating various types of graphs, analyzing network structures, designing algorithms and drawing networks with ease and flexibility.

Installation

To install the latest version of NetworkX, simply run:

pip install networkx

Creating Graphs

NetworkX supports several types of graphs:

  • Graph(): undirected graph
  • DiGraph(): directed graph
  • MultiGraph(): undirected graph with parallel edges
  • MultiDiGraph(): directed graph with parallel edges

Let’s begin with a basic undirected graph:

Python
import networkx as nx

# Create an empty graph
G = nx.Graph()

Adding Nodes

You can add nodes one at a time or in batches:

Python
# Add individual nodes
G.add_node(1)
G.add_nodes_from([2, 3, 4, 7, 9])

Output:

Creating Nodes

After this step, your graph G has 6 nodes.

Adding Edges

Edges connect the nodes in your graph:

Python
# Add individual edges
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)

# Add multiple edges at once
G.add_edges_from([(1, 7), (2, 9)])

Output:

Creating Edges

Note: Since it's an undirected graph, the edge (1, 2) is the same as (2, 1).

Removing Nodes and Edges

You can remove nodes and edges just as easily:

Python
G.remove_node(3)             # Removes node 3
G.remove_edge(1, 2)          # Removes edge between node 1 and 2

Output:

Removing Nodes and Edge

Network Analysis with NetworkX

NetworkX allows you to perform deep analysis of your graph:

Python
# All nodes
print(G.nodes())            
# All edges
print(G.edges())             

# Number of nodes and edges
print(G.number_of_nodes()) 
print(G.number_of_edges())  

# Degree of a node (number of connections)
print(G.degree(2))          

# Neighbors of a node
print(list(G.neighbors(2)))

# Clear the graph (remove all nodes and edges)
G.clear()

Output

[1, 2, 4, 7, 9]
[(1, 4), (1, 9), (1, 7), (2, 4), (2, 9)]
5
5
2
[4, 9]

Explanation:

  • G.nodes() returns a list of all nodes currently in the graph.
  • G.edges() gives a list of all the edges (i.e., node pairs that are connected).
  • G.number_of_nodes() returns the count of total nodes.
  • G.number_of_edges() returns the count of total connections.
  • G.degree(2) gives the number of connections the node 2 has (its degree).
  • list(G.neighbors(2)) lists all nodes that are directly connected to node 2.

Article Tags :
Practice Tags :

Explore