How can I have access to connected components using networkx?

Viewed 204

I'm using networkx.connected_components to have a list of subgraphs of my main graph, but all it returns is this :

<generator object connected_components at 0x000001AC12663820>

How can I have access to a list of the connected components? what should I add to the code below to do this? :

G = nx.Graph()
components= nx.connected_components(G)

separated_graphs = list(components)

print(separated_graphs)
1 Answers

Your code above does actually return a blank list as it should (i.e. it evaluates the generator object). Instead, print(components) outputs the generator object without evaluating it as you noted.

The output for a non-trivial example still may not be what you expect, however, since nx.connected_components() returns subsets of nodes and not subgraphs. The docs for nx.connected_components() has a nice example showing best practice for actually accessing the subgraphs:

S = [G.subgraph(c).copy() for c in nx.connected_components(G)]
Related