How do I get nodes from the specific edge in the networkx?

I want to compare nodes of different edges in the graph. How can I get the nodes(n1 and n2) from the edge(n1,n2)?


An edge in NetworkX is defined by its nodes, so I’m not really sure what you’re asking here. A specific edge in the graph is just a tuple of nodes, with an optional weighting.

import networkx as nx
g = nx.Graph()


[(1, 2), (2, 3)]

As you can see, the list of edges explicitly provides the nodes of each edge.

Update: Does this do what you want?


import networkx as nx
import random

g = nx.Graph()

random_edge = random.choice(g.edges())

print 'Randomly selected edge is:', random_edge
print 'Nodes are', random_edge[0], 'and', random_edge[1]