Every NetworkX task starts with building a graph and asking basic questions about it.
A graph is a set of nodes connected by edges. In NetworkX, G = nx.Graph() creates an empty undirected graph. Any hashable Python object can be a node: numbers, strings, tuples, even custom objects.
Adding structure:
G.add_node("a")andG.add_nodes_from(["b", "c"])G.add_edge("a", "b")adds both nodes automatically if missingG.add_edges_from([("b", "c"), ("c", "d")])G.remove_node(n)also removes its edges;G.remove_edge(u, v)
Querying:
G.number_of_nodes()(orlen(G)),G.number_of_edges()list(G.nodes),list(G.edges)list(G.neighbors("c"))orG["c"], its adjacencyG.degree("c")for one node,dict(G.degree)for allG.has_edge("a", "b"),"a" in G
A plain Graph is undirected and simple: adding the same edge twice keeps one edge, and ("a", "b") is the same as ("b", "a"). Self-loops are allowed.
nx.Graph(edge_list) builds a graph in one step, and print(G) gives a one-line summary such as Graph with 4 nodes and 3 edges. The convention is import networkx as nx.
Example
import networkx as nx
G = nx.Graph()
G.add_edge("ana", "ben")
G.add_edges_from([("ben", "cy"), ("cy", "ana"), ("cy", "di")])
G.add_node("eve") # isolated node
G.add_edge("ben", "ana") # duplicate: ignored
print(G) # Graph with 5 nodes and 4 edges
print(sorted(G.neighbors("cy"))) # ['ana', 'ben', 'di']
print(G.degree("cy"), dict(G.degree)["eve"]) # 3 0
print(G.has_edge("di", "cy")) # True (undirected)
G.remove_node("cy") # its edges go too
print(G.number_of_edges()) # 1Remember
nx.Graph()is undirected and simple; any hashable value can be a node- Adding an edge adds its nodes
G.neighbors,G.degree,G.has_edgeanswer the basic questions
Watch out for
- Using a mutable object like a list as a node: nodes must be hashable.