API Reference

NetworkX

Python library for creating, manipulating, and analyzing complex networks with many graph algorithms built in.

Official Documentation ↗
CompatibilityThis documentation covers version v3. Check the official docs for the latest API surface.

Installation

pippip install networkx

Methods

Overview

NetworkX is a Python library for creating, manipulating, and analyzing complex networks with a large set of graph algorithms. This reference lists the most frequently used APIs with accurate signatures and runnable snippets.

Core APIs

  • Graph.add_edge — Builds an undirected graph and adds edges with optional attributes such as weight.
  • nx.shortest_path — Computes the shortest path between two nodes, optionally weighted.
  • nx.pagerank — Ranks nodes by importance using the PageRank algorithm.

Example

import networkx as nx

g = nx.Graph()
g.add_edge('a', 'b', weight=2)
g.add_edge('b', 'c', weight=1)
print(g.number_of_nodes())

Notes

Graph class choice matters: directed or multigraph features change which algorithms apply. Performance is pure Python, so very large graphs need other tools.

Verification

Build a small weighted graph and confirm shortest_path returns the expected node sequence.

Errors

The official API reference declares the following error types:

API reference evidence

Fetched from official sources on 2026-11-08T17:41:29+08:00 via WebFetch https://networkx.org/documentation/stable/reference/generated/networkx.Graph.add_edge.html 与 shortest_path 页均返回 GitHub Pages 404(2 次失败);改用 PowerShell Invoke-WebRequest 下载官方仓库 main 分支源码 docstring(raw.githubusercontent.com/networkx/networkx/main: networkx/classes/graph.py、networkx/algorithms/shortest_paths/generic.py、networkx/algorithms/link_analysis/pagerank_alg.py)并 Grep 提取.

FAQ

Which graph classes should I use?
Use Graph for undirected, DiGraph for directed, and MultiGraph when parallel edges matter; the choice changes algorithm behavior.
Can I read a graph from a file?
Yes. networkx provides readers such as read_edgelist and read_graphml plus writers to persist the same formats.
How do I handle large graphs?
Pure Python algorithms have limits; for very large graphs consider sparse matrix implementations via scipy or an external graph engine.