networkX DiGraph: list all neighbouring nodes disregarding edge direction

Question:

Is there a better way to obtain the list of nodes that connect to a given one in a directed graph via a single edge (whether inbound or outbound)?

Here is what I came up with. First I build and draw a demo DiGraph:

import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
    ('A','B'),
    ('B','C'),
    ('C','D'),
    ('D','E'),
    ('F','B'),
    ('B','G'),
    ('B','D'),
])
nx.draw(
    G,
    pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
    node_color='#FF0000',
    with_labels=True
)

simple demo directed graph

and now I’d like to get all "neighbouring nodes for node ‘B’" and currently I do so with:

node= 'B'
incoming = [n for n in G.predecessors(node)]
outgoing = [n for n in G.successors(node)]
neighbours = incoming + outgoing 
print(neighbours)
['A', 'F', 'C', 'G', 'D']

Is there a simpler, better, faster way of achieving this result?

Asked By: Robert Alexander

||

Answers:

From the documentation of the class nx.DiGraph

the edges reporting object is often more convenient:

>>> for u, v, weight in G.edges(data="weight"):
...     if weight is not None:
...         # Do something useful with the edges
...         pass

What you want can be achieved using G.edges and a list comprehension like this

[
    other_node
    for edge in G.edges()
    for other_node in edge
    if node in edge and other_node != node
]
Answered By: Nicolas Martinez

I would use networkx inbuilt methods instead

from networkx import*
list(all_neighbors(G, 'B'))
['A', 'C', 'G', 'D', 'F']
Answered By: wwnde
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.