I have extracted a list of all connected components of a graph G as list of subgraphs this way:
sg = list(nx.connected_component_subgraphs(G))
Then I made some counts:
n_conn_comp = nx.number_connected_components(G) # >>> 172305
n_isolated_nodes = len(nx.isolates(G)) # >>> 152403
n_subgraf_dimensionMoreThan1 = n_conn-comp - n_isolated_nodes # >>> 19902
len(sg) # >>> 172305
Until here everything ok. Then my task is to extract a list of connected components with dimension bigger than 1 (at least 2) as a list of subgraph. 'Cause there is not such a library command in NetworkX (or Am I wrong?!), I tried doing it this way:
for elem in sg:
if len(elem) == 1:
sg.remove(elem)
This code gives no error. I expected that now len(sg) was = n_subgraf_dimensionMoreThan1, and so = 19902. So I checked this:
len(sg)
But the result is:
>>> 91620
Much more than expected (19902) I really can't find out what went wrong. I also tried the same code to remove strings of len 1 into a list of strings of different len, and it works fine and correctly.
May with list of subgraphs things go in different way..
Any suggestion?! Thanks a lot
I believe it's because you are removing items from the same list you are iterating through. For example:
>>> sg = range(20)
>>> for i in sg:
sg.remove(i)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
The solution is to make one copy of sg to iterate through and another copy to call your .remove() method on.