Reputation: 191
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?
Upvotes: 8
Views: 11767
Reputation: 756
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))
Upvotes: 5
Reputation: 23129
There are already couple methods provided by the networkx
package:
remove_edges_from
: remove all the edges from a graphclear
: remove all the nodes and edges from a graphwhy simply not use any of them for your requirement? e.g.,
G.remove_edges_from(G.edges())
should do the job instead of defining yet another function to do the same. For example, consider the following code run on python 3.5
in windows 11 with jupyter notebook
:
import platform
print(platform.python_version())
# 3.5.4
import networkx as nx
print(nx.__version__)
# 1.11
G=nx.complete_graph(5)
print(G.edges())
# [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
G.remove_edges_from(G.edges())
print(G.edges())
# []
Upvotes: 1
Reputation: 114488
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.
Upvotes: 10