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?
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With