0

I created a graph G and add two nodes. Then I find the connected components of this graph and assign it to variable a.

import networkx as nx
G = nx.Graph()
G.add_node('a')
G.add_node('b')
a = nx.connected_components(G)

Then I print the variable a out:

>> print(list(a))

and I get the result as:

[set(['a']), set(['b'])]

After this, I print a again using the same prompt, but got nothing:

[]

I'm very curious about this. I print the connected components out once, and it seems that they disappeared?! Why?!

1 Answers1

0

nx.connected_components creates something called a "generator". You can learn more about them here: Understanding Generators in Python

The big point is that a generator doesn't calculate something until you ask for it, and once it calculates it, it yields the thing and then it's gone from memory. So for example if you do

for component in nx.connected_components(G):
     action(component)

It will find one component in G, and then the code will move to whatever action is being done. The first component it found is stored in component and the generator itself no longer remembers it. When the action is complete, the next step of the loop begins and the generator will do all the calculations to find the next component. This is great for preserving memory and prevents python from spending lots of time calculating things --- if you might leave the loop early it doesn't have to calculate the later components.

In your case, you did list(a). Here a is the generator. list needs all of the things in a. So they all get calculated and put into a list. Now there's nothing left in a. It is "exhausted". This is normal generator behavior. The list is gone because it didn't get saved with a name.

For what I think you want, you should say:

import networkx as nx
G = nx.Graph()
G.add_node('a')
G.add_node('b')
b = list(nx.connected_components(G))

Here the generator is exhausted, but the values it created are stored in the list b, which you can use repeatedly.

Community
  • 1
  • 1
Joel
  • 22,598
  • 6
  • 69
  • 93