How do you find nodes with no outgoing edges in networkx?

Viewed 4332

I am trying to find nodes with no outgoing edges in a digraph in networkx.

Is there a way to do this? I found isolates but that finds edges without incoming or outgoing edges, and I don't want that.

3 Answers

"methods that returned an iterator have been removed"

in NetworkX 2.x, so @fuglede's answer needs a minor update:

(node for node, out_degree in G.out_degree() if out_degree == 0)

The view/reporting API provided by .out_degree in 2.x provides an OutDegreeView over (node, out_degree) pairs, making this approach slightly simpler than @Fony Lew's.

I had a problem with out_degree_iter() as it returns an error. So I searched for other solutions on NetworkX documentation and found this is working. (G is a DiGraph)

[node for node in G.nodes if G.out_degree(node) == 0]

Note, in case of finding incoming degree or edges. You can just simply change from out_degree to in_degree

Ref: networkx.DiGraph.out_degree

Related