Get all edges linked to a given node in a networkx graph

PythonGraph TheoryNetworkx

Python Problem Overview


Just wondering if there is convenient networkx function that returns a list of edges connected to a given node (or nodes) (e.g. my_node_name) in a graph (e.g. G).

I can do it this way:

edlist=[]
for ed in G.edges():
     if 'my_node_name' in ed:
            edlist.append(ed)

but expect there might be a better way?

Python Solutions


Solution 1 - Python

If the graph is undirected, you can use

G.edges(node)

In networkx 2.x this is an EdgeDataView object. In networkx 1.x this is a list - if you want a generator in 1.x rather than getting the whole list, G.edges_iter(node) works (this no longer exists in 2.x).

If the graph is directed the command above will not give the in-edges. Use

G.in_edges(node)
G.out_edges(node) 

These are views in 2.x. In 1.x these are lists and there are generator options: G.in_edges_iter(node) and G.out_edges_iter(node)

Solution 2 - Python

You can use the method edges on a node for an un-directed graph:

G.edges(['my_node_name'])

or the function edges

networkx.edges(G, ['my_node_name'])

But for directed graphs the above method will only give the out-edges; there you need to call and combine both in_edges() and out_edges().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionatomh33lsView Question on Stackoverflow
Solution 1 - PythonJoelView Answer on Stackoverflow
Solution 2 - PythondonkopotamusView Answer on Stackoverflow