Karagounis Z
Karagounis Z

Reputation: 191

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?

Upvotes: 8

Views: 11767

Answers (3)

Maxime Beau
Maxime Beau

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

Sandipan Dey
Sandipan Dey

Reputation: 23129

There are already couple methods provided by the networkx package:

  1. remove_edges_from: remove all the edges from a graph
  2. clear: remove all the nodes and edges from a graph

why 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

Mad Physicist
Mad Physicist

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

Related Questions