Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all edges from a graph in networkx

I perform the following python commands, trying to remove all edges from the graph G.

def method(G):
  edges = G.edges()
  G.remove_edges_from(edges)

But it yields the following error:

RuntimeError: dictionary changed size during iteration.

It seems like the command iterates through the edges, but when I remove an edge, it modifies the iterator during iteration, which causes an error.

How do I get around this?

like image 921
Karagounis Z Avatar asked Sep 10 '18 05:09

Karagounis Z


2 Answers

You may want to look into the method create_empty_copy, which copies the nodes without the edges into a new graph. The docs literally read:

Return a copy of the graph G with all of the edges removed.

If you wanted to keep the original graph as-is, you could do something like

edges = list(G.edges)

to ensure that you copy the edges before requesting their removal.

like image 165
Mad Physicist Avatar answered Nov 15 '22 08:11

Mad Physicist


G.edges is an 'edges view' and G.edges() an 'edges data view' which are bound to the graph and are updated whenever the graph is altered.

You need to convert them into a self-contained independent variable which will not be updated each time an edge is removed from the graph, for instance by converting the edge view into a list or a dictionary.

Hence you can use these workarounds:

G.remove_edges_from(list(G.edges()))
G.remove_edges_from(list(G.edges))
G.remove_edges_from(dict(G.edges))
like image 33
Maxime Beau Avatar answered Nov 15 '22 06:11

Maxime Beau