Graphs, nodes and edges

NetworkX · Essentials · 10 min

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") and G.add_nodes_from(["b", "c"])
  • G.add_edge("a", "b") adds both nodes automatically if missing
  • G.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() (or len(G)), G.number_of_edges()
  • list(G.nodes), list(G.edges)
  • list(G.neighbors("c")) or G["c"], its adjacency
  • G.degree("c") for one node, dict(G.degree) for all
  • G.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())             # 1

Remember

  • 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_edge answer the basic questions

Watch out for

  • Using a mutable object like a list as a node: nodes must be hashable.

Check yourself

  1. You call G.add_edge(1, 2) twice on an nx.Graph. How many edges are there?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: networkx.org/documentation/stable/tutorial.html