Reputation: 633
Why is 0,1,2
added to nodes upon adding edges (last print statement in code below)?
import networkx as nx
G = nx.Graph()
G.add_nodes_from([(0,0,0), (1,0,0), (1,1,0)])
print(G.nodes) # >> [(0, 0, 0), (1, 0, 0), (1, 1, 0)]
edges = [(0, 1),(1,2)]
G.add_edges_from(edges)
print(G.nodes) # >> [(0, 0, 0), (1, 0, 0), (1, 1, 0), 0, 1, 2] ???
Upvotes: 1
Views: 62
Reputation: 181735
In NetworkX, nodes are identified by any hashable object. So the add_nodes_from
call adds three nodes, each a tuple:
(0, 0, 0)
(1, 0, 0)
(1, 1, 0)
Maybe you understood this already.
add_edges_from
takes an iterable of 2-tuples (or 3-tuples), where each tuple identifies two nodes. So (0, 1)
adds an edge between nodes 0
and 1
. These are node identifiers, not indices! And since these nodes don't exist yet, they are automatically added. This is documented:
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when adding nodes or edges that already exist.
What you probably meant to do is use the nodes' identifiers directly:
edges = [((0, 0, 0), (1, 0, 0)), ((1, 0, 0), (1, 1, 0))]
G.add_edges_from(edges)
Upvotes: 3