1

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

mik.ferrucci
  • 121
  • 1
  • 2
  • 13
  • Possible duplicate of [Remove items from a list while iterating](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – Joel Nov 22 '16 at 19:37
  • You are right, in fact i finally found the solution reading the post you linked. May I have to remove my question..?! – mik.ferrucci Nov 22 '16 at 21:36

2 Answers2

1

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.

Brian Huey
  • 1,550
  • 10
  • 14
0

I finally solved this way: (list comprehension )

sg_MoreThan1 = [el for el in sg_notdeg if len(el)!=1]

In fact:

len(sg_MoreThan1)
>>> 19902

Thanks anyway.

mik.ferrucci
  • 121
  • 1
  • 2
  • 13