Sib
Sib

Reputation: 483

How to access the first neighbor of a node in NetworkX?

I created a graph of TestClass objects in NetworkX. I have two TestClass objects obj1 and obj2 and I want to connect their first neighbors.

Code

first_node = [node for node in G.nodes() if node==obj1][0]
second_node = [node for node in G.nodes() if node==obj2][0]                
G.add_edge(first_node.neighbours[0], second_node.neighbours[0])

I get an error message that TestClass object has no attribute neighbors.

How do you access these two objects as nodes in the Graph to work with their neighboring nodes?

Upvotes: 1

Views: 1314

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24134

Neighbors are accessed using the method Graph.neighbors(n), where n is a node.

Since G.neighbors returns an iterator over the neighboring nodes, to use a list accessor, you would first need to wrap the iterator in a list initializer.

G.add_edge(list(G.neighbors(first_node))[0], list(G.neighbors(second_node))[0])

A cleaner way would be to call next() on the iterators, which avoids creating new list objects and eliminates the index accessors.

G.add_edge(next(G.neighbors(first_node)), next(G.neighbors(second_node)))

Upvotes: 1

Related Questions